最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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 e 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

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 e 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

Share Improve this question asked Apr 7, 2022 at 11:27 giuseppegiuseppe 311 silver badge2 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

I got the same. I found a solution here : https://npmmirror./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

If your proxy works with GET but not with payload-requests (PUT/POST), then you might have one of these issues:

  • Body-parser is used. In that case, see https://www.npmjs./package/http-proxy-middleware#intercept-and-manipulate-requests

    import { createProxyMiddleware, fixRequestBody } from 'http-proxy-middleware';
    const proxy = createProxyMiddleware({
        onProxyReq: fixRequestBody
    });
    
  • The backend or ingress/load-balancer of your cloud provider might be checking additional headers except "host", which is the only one that changeOrigin: true is overwriting. This was the problem for me when working with GCP. In that case, overwrite additional headers manually:

    const replaceOrigin = (proxyReq: any, headerKey: string, newOrigin: string) => {
      const headerValue = proxyReq.getHeader(headerKey);
      typeof headerValue === 'string' &&
        proxyReq.setHeader(headerKey, headerValue.replace(new URL(headerValue).origin, newOrigin));
    };
    const proxy = createProxyMiddleware({
        target: targetBase,
        changeOrigin: true, // replaces only host header but not referer and origin
        configure: (proxy: any) => {
           proxy.on('proxyReq', (proxyReq: any) => {
              replaceOrigin(proxyReq, 'referer', targetBase);
              replaceOrigin(proxyReq, 'origin', targetBase);
        });
    });
    

I have been using http-proxy-middleware through VITE, it worked there as well. What did not work for some reason, was using onProxyReq(proxyReq: any) to getHeader/setHeader, so I had to use configure with proxy.on(...) like in the example above.

发布评论

评论列表(0)

  1. 暂无评论