简体   繁体   中英

How to query a request at Nodejs Proxy Server?

I have a Nodejs Proxy server like this:

`var http = require('http'),
httpProxy = require('http-proxy');

var proxy = httpProxy.createProxyServer({});

proxy.on('proxyReq', function(proxyReq, req, res, options) {
  proxyReq.setHeader('X-Special-Proxy-Header', 'foobar');
});

var server = http.createServer(function(req, res) {
    console.log(req.body);
  proxy.web(req, res, {
    target: 'http://localhost:3000'
  });
 });

console.log("listening on port 9000")
server.listen(9000);`

What i want is get the req.body at the proxy server when i post a request to the Origin server, go through the proxy server. I used "console.log(req.body);" at both proxy server and the origin server. I get the body object {"id": "user003"} at origin server, but undefined at the proxy server. So how can i get the req.body at proxy server?

I suspect the problem here is that you don't have a body parser on your proxy server, but do have one on your origin.

req.body itself isn't set by node. Instead, you have to handle events emitted by the req stream:

let body = '';
req.on('data', (data) => {
    // data is a buffer so need toString()
    body += data.toString();
});

req.on('end', () => {
    // at this point you'll have the full body
    console.log(body);
});

You can make this easier with a body parser (eg https://www.npmjs.com/package/body-parser ) but since you're running a proxy server, you probably don't want to parse the entire req stream before forwarding onto your origin. So I'd maybe stick with handling the events.

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