使用Node.js/formidable中止用户请求

Kam*_*tka 11 web-services http httprequest node.js

我正在使用formidable来接收带有node.js的文件上传.我将一些字段与多部分请求中的文件一起发送.

一旦某些字段到达,我就能够验证请求的真实性,并且我想中止整个请求,如果这不正确以避免资源浪费.

我没有找到正确的方法来中止传入的请求.我尝试使用req.connection.destroy();如下:

form
.on('field', function(field, value) {
    fields[field] = value;
    if (!fields['token'] || !fields['id'] || !fields['timestamp']) {
        return;
    }
    if (!validateToken(fields['token'], fields['id'], fields['timestamp'])) {
        res.writeHead(401, {'Content-Type' : 'text/plain' });
        res.end('Unauthorized');
        req.connection.destroy();
    }
})
Run Code Online (Sandbox Code Playgroud)

但是,这会触发以下错误:

events.js:45
        throw arguments[1]; // Unhandled 'error' event
                       ^
Error: Cannot resume() closed Socket.
    at Socket.resume (net.js:764:11)
    at IncomingMessage.resume (http.js:254:15)
    at IncomingForm.resume (node_modules/formidable/lib/incoming_form.js:52:11)
    at node_modules/formidable/lib/incoming_form.js:181:12
    at node_modules/formidable/lib/file.js:51:5
    at fs.js:1048:7
    at wrapper (fs.js:295:17)
Run Code Online (Sandbox Code Playgroud)

我也试过,req.connection.end()但文件不断上传.

有什么想法吗?提前致谢!

the*_*ejh 5

问题是强大的人不明白你想要它停止.试试这个:

req.connection.destroy();
req.connection.resume = function(){};
Run Code Online (Sandbox Code Playgroud)

当然,这是一个有点难看的解决方法,我在github上打开一个问题.