简体   繁体   中英

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:

├── http-proxy-middleware@2.0.4
└─┬ react-scripts@5.0.0
  └─┬ webpack-dev-server@4.7.4
    └── http-proxy-middleware@2.0.4 deduped

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM