Node.js: Disconnect http request connection before

2019-07-25 16:05发布

问题:

I'm writing a http server with Node.js.

I have a client to upload a large file to this server via HTTP POST(multipart/data).

I want to accept the only connection which upload the file with valid filename.(I have some conditions.) The invalid filename connection should be disconnected before the server retrieves the data.

I have no idea how to disconnect the http request connection and return the proper http response.

The http request has only req.pause() method which isn't an answer. and if I call req.connection.end(), the response.writeHeader()/write() doesn't send the response.

回答1:

I think you'll need to send a response.end() to send your writeHeader()/write() calls, followed by a req.connection.end() to end the request without receiving any further data.



回答2:

I would have thought the following should work since the request and response objects share the same socket... but it seems unreliable. Maybe it's a bug in node?

request.connection.allowHalfOpen = false
response.writeHead 500, 
    'Access-Control-Allow-Origin' : '*'
response.end()


标签: http node.js