有一个简单的形式,如下面的 js Fiddle http://jsfiddle.net/UdugW/我正在将一些表单数据发布到我的 node.js 应用程序(基于 sails.js)。这是 product
模型中的 Controller 功能之一:
image_upload: function(req, res) {
if (req.method.toLowerCase() == 'post') {
console.log("request: " + util.inspect(req.body));
if( req.files && req.files.product_image){
fs.readFile(req.files.product_image.path, function (err, data) {
var imageName = req.files.product_image.name;
if(!imageName){
console.log("There was an error with image upload : " + util.index(req.files.product_image));
res.redirect("/product/new_product");
res.end();
} else {
var newPath = UPLOAD_PATH + imageName;
/// write file to uploads/fullsize folder
fs.writeFile(newPath, data, function (err) {
res.writeHead(200, {'content-type': 'text/plain'});
res.end();
return;
});
}
});
}
}else if (req.body) {
console.log("product_name: " + product_name);
console.log("product_price: " + product_price);
console.log("product_description: " + product_description);
res.writeHead(200, {'content-type': 'text/plain'});
res.end();
}
else{
console.log("request err");
res.writeHead(500, {'content-type': 'text/plain'});
res.end();
}
},
当我没有选择要上传的图像时出现问题,然后我的 POST 请求超时。知道为什么会发生这种情况吗?
最佳答案
9/10 使用 node.js 应用程序时,当出现超时时,您很可能忘记关闭套接字(至少根据我的经验)。在你的情况下也没什么不同:-)
这里是问题所在:你有这个 if 语句
if( req.files && req.files.product_image){
但是这个可怜的家伙没有匹配的 else 语句 :-( 因此,如果该条件不成立……好吧,什么也不会发生。执行基本上刚刚结束,浏览器将永远等待……。
只需在其中添加一个带有 res.end()
的 else 语句,就可以了。
像这样
if( req.files && req.files.product_image){
//all the stuff you already have for when it matches
}else{
console.log("No files were included in the post");
res.end();
}
关于javascript - 在输入类型 = 文件中没有选择文件的情况下提交表单超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21372345/