简体   繁体   English

HTTP POST 正文未附加在使用 http-proxy-middleware 的代理请求中

[英]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: *");我正在开发一个 React 应用程序,我需要向远程 API 发出 POST 请求,在其中设置header("Access-Control-Allow-Origin: *"); to disable the CORS policy.禁用 CORS 策略。

However when I contact the server, some CORS policy issues come out, so I setuped a proxy server through http-proxy-middleware.但是当我联系服务器时,出现了一些 CORS 策略问题,所以我通过 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:这是 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 macOS 大苏尔 v11.5.2
Node v16.13.2节点 v16.13.2

Details of the http-proxy-middleware configuration: http-proxy-middleware 配置的详细信息:

├── 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 .我在这里找到了一个解决方案: https://npmmirror.com/package/http-proxy-middleware/v/1.2.0-beta.1

Add this in your createProxyMiddleware parameters:将此添加到您的 createProxyMiddleware 参数中:

onProxyReq: fixRequestBody onProxyReq: fixRequestBody

PS: it's the same as 60 second timeout in http-proxy-middleware i think PS:我认为这与http-proxy-middleware 中的 60 秒超时相同

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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