Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTTP POST body not attached in the proxied request using http-proxy-middleware

I'm developing a React application and I need to make a POST request to a remote API in which I set header("Access-Control-Allow-Origin: *"); to disable the CORS policy.

However when I contact the server, some CORS policy issues come out, so I setuped a proxy server through http-proxy-middleware.

The problem is that the request is correctly proxied but without body and I cannot understand why. Can someone help me?

Here's the setupProxy.js:

    const bodyParser = require('body-parser')
    
    module.exports = function(app) {
    
       // restream parsed body before proxying
     var restream = function(proxyReq, req, res, options) {
       if (req.body) {
           let bodyData = JSON.stringify(req.body);
           // incase if content-type is application/x-www-form-urlencoded -> we need to change to application/json
           proxyReq.setHeader('Content-Type','application/json');
           proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
           // stream the content
           proxyReq.write(bodyData)
           proxyReq.end();
           
       }
     }
     
     app.use(bodyParser.json());
     app.use(bodyParser.urlencoded());
     app.use(
       '/api/*',
       createProxyMiddleware({
         target: 'https://<domain>',
         changeOrigin: true,
         pathRewrite: {
           '^/api/': '<path>'
         },
         logLevel:'debug',
         onProxyReq: restream,
         
       })
     );  
    
     
    };

Details of the system:

macOS Big Sur v11.5.2
Node v16.13.2

Details of the http-proxy-middleware configuration:

├── [email protected]
└─┬ [email protected]
  └─┬ [email protected]
    └── [email protected] deduped

like image 337
giuseppe Avatar asked Nov 28 '25 04:11

giuseppe


1 Answers

I got the same. I found a solution here : https://npmmirror.com/package/http-proxy-middleware/v/1.2.0-beta.1.

Add this in your createProxyMiddleware parameters :

onProxyReq: fixRequestBody

PS : it's the same as 60 second timeout in http-proxy-middleware i think

like image 130
Franck Besson Avatar answered Nov 29 '25 18:11

Franck Besson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!