For now I have following code:
app.post('server1',function(req,res,next){ var request = require('request'); req.pipe(request.post('server2')).pipe(res); }
So this does not work - request is not even piped to server2 - I checked it and there is no incoming request.
I solved points 1 & 2 like this:
var bodyParser = express.bodyParser(); app.use(function(req,res,next){ if(req.path == '/server1' && req.method == 'POST') { return next(); } else { bodyParser(req,res,next); } });
Not very nice but it works - it just disables bodyparser for a single route (POST /server1).
But I still don't know how to obtain json response body from piped request - I have following code:
app.post('/server1',function(req,res,next){ var request = require('request'); var pipe = req.pipe(request.post('/server2')); pipe.on('end',function(){ var res2 = pipe.response; console.log(res2); }); });
res2
object has correct statusCode and headers and so on but it does not contain body - how I can get this from the res2
object? /server2
returns some data in json but I dont know how to read it from response...
ExpressJS is a NodeJS module; express is the name of the module, and also the name we typically give to the variable we use to refer to its main function in code such as what you quoted. NodeJS provides the require function, whose job is to load modules and give you access to their exports.
pipe() method is used to attach a readable stream to the writable Stream. Stream. pipe() method is also used in file streams in NodeJs. Stream. pipe() can be used for HTTP requests and response objects.
It is unmaintained Express has not been updated for years, and its next version has been in alpha for 6 years. People may think it is not updated because the API is stable and does not need change. The reality is: Express does not know how to handle async/await .
Express. js Request and Response objects are the parameters of the callback function which is used in Express applications. The express. js request object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on.
It doesn't work because bodyParser intercepts all the bodies with parsers
I think you're almost there. You should listen on data
events on the pipe to collect the response:
app.post('/server1',function(req,res,next) { var request = require('request'); var pipe = req.pipe(request.post('/server2')); var response = []; pipe.on('data',function(chunk) { response.push(chunk); }); pipe.on('end',function() { var res2 = Buffer.concat(response); console.log(res2); // don't forget to end the 'res' response after this! ... }); });
However, since you solved the "bodyParser() getting in the way" problem, you can also use your initial pipe setup if you just want to return the response generated by server2 (also, be sure to use proper URL's when using request
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With