如何在nodejs中关闭请求?
我所拥有的:
我正在使用 node.js 和 Express 框架,我正在构建一个可以上传文件的表单,我正在使用 node-formidable为了这。
有什么问题
我的问题是,如果我发现上传的文件有错误,我无法关闭请求。我想检查文件类型、大小等。这样我就可以上传正确的文件,而文件实际上没有上传,所以我不会浪费时间。
所以问题是我无法停止HTTP请求。
我已经尝试过
以下是我到目前为止所尝试过的:
request.connection.destroy();
response.end('something went wrong...');
我假设 connection.destroy()
中止请求,我知道这一点是因为它会触发强大的表单中止事件 (form .on('abort', function(){ ... })
) 但文件仍在上传,文件上传后响应并未立即到达。
那么我应该如何关闭 HTTP 请求,并将消息发送回客户端?
编辑: 还有其他事情,当我不使用 response.end()
时它会起作用,除了客户端等待答案之外,这很奇怪:\
What I have:
I'm using node.js with the express framework and I'm building a form where I can upload files, I'm using node-formidable for this.
What's the problem
My problem is that I can't close the request if I found an error with the uploaded files. I want to check file types, size etc.. So I can get the proper files uploaded, and the files are actually not uploaded so I don't waste time.
So the problem is that I can't stop the HTTP request.
What I have tried
Here is what I have tried so far:
request.connection.destroy();
response.end('something went wrong...');
I assume that the connection.destroy()
aborts the request, and I know this because it fires the formidables form abort event (form.on('abort', function(){ ... })
) But the file is still uploading, and the response doesn't arrives just after the file was uploaded.
So how should I close the HTTP Request, and send a message back to the client?
EDIT:
And something else, when I don't use response.end()
then it works, except that the Client waits for the the answer, it's weird :\
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正确的方法是:
来源:https://groups .google.com/forum/?fromgroups=#!topic/nodejs/2gIsWPj43lI
The correct way for doing this is:
Source: https://groups.google.com/forum/?fromgroups=#!topic/nodejs/2gIsWPj43lI
尝试使用以下代码:
当服务器端验证失败时,给出如下响应:
res.json({'IsFileUploaded':'false', 'requiredFileSize': '1000bytes', 'actualFileSize': '800bytes', 'AlertMsg':'文件大小应至少为 1000 字节.. ..'})
它会关闭连接,并且您可以以 JSON 格式传递数据
Try with following code:
When your server side validation fails, give a response like:
res.json({'IsFileUploaded':'false', 'requiredFileSize': '1000bytes', 'actualFileSize': '800bytes', 'AlertMsg':'File size should be at least 1000 bytes....'})
It closes connection as well as you can pass your data in JSON format