如何在nodejs中关闭请求?

发布于 2024-12-01 21:51:00 字数 786 浏览 1 评论 0原文

我所拥有的:

我正在使用 node.jsExpress 框架,我正在构建一个可以上传文件的表单,我正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

放手` 2024-12-08 21:51:01

正确的方法是:

request.pause();
response.status = 400;
response.end('something went wrong...');

来源:https://groups .google.com/forum/?fromgroups=#!topic/nodejs/2gIsWPj43lI

The correct way for doing this is:

request.pause();
response.status = 400;
response.end('something went wrong...');

Source: https://groups.google.com/forum/?fromgroups=#!topic/nodejs/2gIsWPj43lI

荒芜了季节 2024-12-08 21:51:01

尝试使用以下代码:

  1. 当服务器端验证失败时,给出如下响应:

    res.json({'IsFileUploaded':'false', 'requiredFileSize': '1000bytes', 'actualFileSize': '800bytes', 'AlertMsg':'文件大小应至少为 1000 字节.. ..'})

    它会关闭连接,并且您可以以 JSON 格式传递数据

Try with following code:

  1. 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文