如标题所示,
如果URL中的数据库ID的变量不存在,如何将URL重定向到错误 如果我有:
router.get('/edit/:id', function (req, res, next) {
res.render('product/edit', { title: 'Express', id: req.params.id });
//console.log(req.params.id); <--- return 4300030
});
如果数据库中不存在req.params.id
如何将其重定向到错误?
我写了一个例子来告诉你我的意思:
router.get('/edit/:id', function (req, res, next) {
fs.readFile('baza.json', 'utf-8', function (error, content) {
if (error) {
res.json({
error: error,
status: false
});
} else {
products = JSON.parse(content);
for (var i = 0; i < products.length; i++) {
if (products[i].id === req.body.id) {
if (products[i].id === req.body.id) {
res.render('product/edit', { title: 'Express', id: req.params.id });
}
else {
res.render('error', { title: 'Error' });
}
}
}
}
})
由于 顺便说一句,我做了两个如果相同,因为我不知道在第二个写什么。
答案 0 :(得分:1)
如果您找到了正确的ID,则想要成功停止,如果找不到任何内容,则需要返回错误:
for (var i = 0; i < products.length; i++) {
if (products[i].id === req.params.id) {
return res.render('product/edit', { title: 'Express', id: req.params.id });
}
}
return res.render("error",{title:"Error"});