fastify/fastify-http-proxy

Didn't get multipart/form-data value from proxy server to main server

amitkTechno opened this issue · 1 comments

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the issue has not already been raised

Issue

Node.js version

14.21.2

Npm version

6.14.17

Fastify version

4.24.3

Description

I am using @fastify/express 2.3.0 and @fastify/http-proxy 9.3.0 and @fastify/multipart 8.0.0. Trying to upload a file using express-fileupload 1.1.10. When making a request with a file, get the file details in proxy server, but didn't get the file details in the main server.

Configuration

const express = require('express');
const router = express.Router();
async function startOrigin() {
  const server = Fastify({
    logger: false,
  })
  server.register(require('@fastify/multipart'));
  server.register(require('@fastify/express')).after(() => {
    server.use(express.urlencoded({ extended: true })); // for Postman x-www-form-urlencoded
    server.use(express.json());
    server.use('/api', router);

  });
  router.post('/hello', async (req, res) => {
    const data = await req.file();
    console.log(data);
    res.json({ hello: 'world' });
  });
  await server.listen();
  return server;
}
async function startProxy(upstream) {
  const proxyServer = Fastify({
    logger: false,
  });
  proxyServer.register(require('@fastify/multipart'));
  proxyServer.register(proxy, {
    upstream,
    undici: true,
    preValidation: async (req, reply) => {
      const data = await req.file();
      console.log(data);
    },
    replyOptions: {
      rewriteRequestHeaders: (req, headers) => {
        return {
          ...headers,
          authorization: 'Bearer token' 
        };
      }
    }
  });
  await proxyServer.listen({ port: process.env.PORT || '3000' });
  return proxyServer;
}

async function run() {
  const origin = await startOrigin();

  const upstream = `http://localhost:${origin.server.address().port}`;

  console.log('origin started', upstream);

  const proxy = await startProxy(upstream);

  console.log('proxy started', `http://localhost:${proxy.server.address().port}`);
}

run();

am I doing wrong something. Please check this.

Thanks in advance

What's happening is that the multipart body is parsed at the proxy and not forwarded through.
To fix remove the use of multipart and preValidation option.