管道响应回调

时间:2018-03-31 13:33:04

标签: node.js express request

使用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)正文被编码。这样做的最佳方式是什么?

1 个答案:

答案 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...'))