这是一个 Node.js 函数。它可以工作,因为坏的 JSON 数据会被踢掉,但它也会闪烁失败的消息。为什么?
// Create document
app.post('/documents.:format?', loadUser, function(req, res) {
/////////////////////////added by adam
//tests to see if the inputed text is valid JSON data
data = req.body.d.data;
console.log("///////////" + data);
try {
type = JSON.parse(data);
console.log(type);
} catch (ex) {
console.log("bad json: "+data);
req.flash('Nope', 'Invalid JSON');
res.redirect('/documents');
return;
}
var d = new Document(req.body.d);
d.user_id = req.currentUser.id;
d.save(function() {
switch (req.params.format) {
case 'json':
res.send(d.toObject());
break;
default:
req.flash('info', 'Document created');
res.redirect('/documents');
}
});
最佳答案
catch
block 包含错误消息和“错误 JSON”记录器,因此由于 block 作用域,它们总是同时发生。
关于json - 为什么我的 req.flash 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5466480/