Can I cancel a HTTP response after headers are sen

2019-09-01 14:59发布

问题:

On a node HTTP server I'm spawning a process and streaming the output to the response.

When the process returns I'd like to indicate to the client if an error occured. Obviously I can't set the HTTP status code as the headers were already sent.

Is there a way to abort the connection?

E.g.

var http = require('http');
http.createServer(function (req, res) {

  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.write('Hello World\n');

  // how do I abort the request at this point 
  // and indicate an error to the client?
  // e.g. curl should return != 0

  res.end();
}).listen(1337, '127.0.0.1');

回答1:

var thirdPartyApp = $express();

thirdPartyApp.use('/error/', function (req, res) {

    console.log('error');

    res.writeHead(200);
    res.write('aye');

    throw 'booboo!';

    res.end();
});

On expressjs this does not kill the node process (probably just need to bind to the error event) but does immediately kill the response, indicating an error to the user without a timeout.



回答2:

I found this in google groups, you can use

  • either req.client.destroy();
  • or res.connection.destroy();

curl will then report

curl: (18) transfer closed with outstanding read data remaining



标签: node.js http