Ilja Ilja - 3 months ago 17
Javascript Question

Unexpected "write after end" error in express

I am trying to proxy an api call from client side through my server for some third party service, reasons for this being CORS issues and adding in a secret key on the server side. I usually get it done in the following way:

app.use('/someService', (req, res) => {
let url = `https://example.com/${config.SECRET_KEY}/endpoint${req.url}`
req.pipe(request(url).pipe(res))
})


this way I can use any ajax library on the client side and perform get request for example:
get: '/someService/params'
and it would normally go through and perform that request and then pipe it back. However now I started getting:


Error: write after end


in express and I am not entirely sure about what could be causing it.

Answer

Your piping is wrong. As it is now, you're piping to res twice (.pipe() returns the argument passed to it for chainability).

Instead try this:

req.pipe(request(url)).pipe(res)

I should point out however that properly proxying the HTTP response is not quite that simple since currently this line will always respond with HTTP status code 200, no matter what the remote server for the middle request responds with. Also, any headers from that response will not be sent to res. With that in mind, you could naively try something like:

var proxiedRes = req.pipe(request(url));
proxiedRes.on('response', function(pres) {
  res.writeHead(pres.statusCode, pres.headers);
  // You will want to add a `pres` 'error' event handler too in case
  // something goes wrong while reading the proxied response ...
  pres.pipe(res);
});