Using NodeJS and Express, I'm proxying a request with the request module. Then, when the response is received, I need to set the cookies to the former response, and send it back to the client.
app.use('/api', function(req, res) {
var options = {
url : constants.API_COMPLETE_URL + '/api' + req.url
};
req.pipe(request(options, function (err, backendResponse) {
if (err) {
res.status(501).send(err);
return;
}
setCookiesToResponse(res, backendResponse);
backendResponse.pipe(res);
}));
});
However, backendResponse.pipe(res.body) the body is encoded. What is the best way of doing this?
const express = require('express')
const request = require('request')
const app = express()
app.use('/', (req, res) => {
// change url accordingly
const proxy = request({ url: 'http://www.google.com' + req.path })
proxy.on('response', proxyResponse => {
// proxyResponse is an object here
res.cookie('yourCookie', 'works!', {
maxAge: 900000,
httpOnly: true
})
}).pipe(res)
// catch errors with proxy.on('error', err => {})
req.pipe(proxy)
})
app.listen(8900, () => console.log('Listening...'))
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