使用NodeJS和Express,我用request
模块代理请求。然后,当收到响应时,我需要将cookie设置为前一个响应,并将其发送回客户端。
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);
}));
});
然而,backendResponse.pipe(res.body)
正文被编码。这样做的最佳方式是什么?
答案 0 :(得分:4)
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...'))