So, I am creating a REST API using node and I have to create a route. Purpose of the route: Act as a proxy server and make a call to a different external website and return the response it gets to the original request. So far, I have the following code and it works:
app.post('/v1/something/:_id/proxy',
    function(req, res, next) {
        // Basically make a request call to some external website and return
        // the response I get from that as my own response
        var opts = {/*json containing proper uri, mehtod and json*/}
        request(opts, function (error, responseNS, b) {
            if(error) return callback(error)
            if(!responseNS) return callback(new Error('!response'))
            return res.json(responseNS.body)
        })
    }
)
My question is, how can I stream this http response that I am getting from the external website. By that, I mean that I want to get the response as a stream and keep returning it as soon as it comes in chunks. Is this possible?
You can pipe the incoming response from an external source straight to a response that your app sends to the browser, like this:
app.post('/v1/something/:_id/proxy',
function(req, res, next) {
    // Basically make a request call to some external website and return
    // the response I get from that as my own response
    var opts = {/*json containing proper uri, mehtod and json*/}
    request(opts, function (error, responseNS, b) {
        if(error) return callback(error)
        if(!responseNS) return callback(new Error('!response'))
        return res.json(responseNS.body)
    }).pipe(res);
});
                        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