上传使用了 formidable, 有些处理用到了 listener, 那么问题来了, 监听是异步的, 如何中断返回结果呢. 看下代码
var received = 0;
form.on('progress', function(bytesReceived, bytesExpected) {
received += bytesReceived;
if (received > 1024*1024) {
res.json({err: "图片过大"})
return;
}
});
...
form.parse(req, function(err, fields, files) {
var file = files.icon;
res.json({url: file.path.replace('public', '')})
});
这个写法是错误的, 会报 Can't set headers after they are sent. 应该如何改进呢
1
broadliyn 2016-07-21 16:31:55 +08:00
检查 http body 的大小不是应该先去检查 http 请求头的 content-length 大小么?
|
2
Arrowing 2016-07-21 16:34:23 +08:00
不太明白你为什么这样写
因为执行了 2 次 res.json 可以加个标识变量 ``` var isSended = false; var received = 0; form.on('progress', function(bytesReceived, bytesExpected) { received += bytesReceived; if (!isSended && received > 1024*1024) { res.json({err: "图片过大"}) return; } }); form.parse(req, function(err, fields, files) { var file = files.icon; !isSended && res.json({url: file.path.replace('public', '')}) }); ``` |
3
Arrowing 2016-07-21 16:35:08 +08:00
忘记加上更改了 0.0
res.json 后面加上 isSended = true; |
5
Sirormy OP @Arrowing 你那个写法不行,没法中断程序的进行,后边是执行写文件的操作,我那样做是先判断文件大小,要阻止后边的代码
|
6
magicdawn 2016-07-21 17:09:33 +08:00
不用自己立标志变量...
res.headerSent https://nodejs.org/dist/latest-v6.x/docs/api/http.html#http_response_headerssent |