Skip to content Skip to sidebar Skip to footer

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.

Solution 1:

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);
});

Post a Comment for "Unexpected "write After End" Error In Express"