开发者

Abort user request with Node.js/formidable

I'm using formidable to receive a file upload with node.js. I send some fields together with a file in a multipart request.

As soon as certain fields arrived, I'm able to validate the authenticity of the request for instance, and I would like to abort the whole request if this is not correct to avoid waisting resources.

I have not found a right way to abort the incoming request. I tried to use req.connection.destroy(); as follow:

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();
    }
})

However, this triggers the following error:

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_modul开发者_JAVA技巧es/formidable/lib/file.js:51:5
    at fs.js:1048:7
    at wrapper (fs.js:295:17)

I also tried req.connection.end() but the file keeps uploading.

Any thoughts? Thanks in advance!


The problem is that formidable didn't understand that you want it to stop. Try this:

req.connection.destroy();
req.connection.resume = function(){};

Of course, this is a somewhat ugly workaround, I'd open an issue on github.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜