Can I cancel a HTTP response after headers are sen

2019-09-01 15:11发布

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

标签: node.js http
2条回答
家丑人穷心不美
2楼-- · 2019-09-01 15:24
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.

查看更多
家丑人穷心不美
3楼-- · 2019-09-01 15:33

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

查看更多
登录 后发表回答