Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pipe response on callback

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?

like image 213
Alessandro Roaro Avatar asked Nov 25 '25 12:11

Alessandro Roaro


1 Answers

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...'))
like image 200
Renato Gama Avatar answered Nov 28 '25 03:11

Renato Gama



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!