node.js - 在 express 中,当满足条件时,如何路由到自定义错误模板?
问题描述
在我的选择语句中,如果 URL 中的参数不正确,我想将用户发送到自定义错误模板。
我尝试设置渲染,但传递的参数不起作用。
#routes.js
router.get('/select-id/', function(req, res) {
var id = req.query.id;
if(id && id.match(/^[0-9]+$/) != null){
mc('SELECT * FROM tasks where ID = ' + id, function (error, results, fields) {
if (error) throw error;
res.render('pug-select-all', {
title: 'Results',
data: results
});
});
}
else {
res.render('error', {status: 500, stack: 'error'});
}
});
#error.pug
extends layout
block content
h1= message
h2= error.status
pre #{error.stack}
我尝试了不同的方法,但我总是在 routes.js 或 pug 模板上遇到错误。如果我像上面的代码一样保留它,我会Cannot read property 'status' of undefined
进入 error.pug
解决方案
查看文档,您应该将响应对象发送为:
res.render('error', { "error": {status: 500, stack: 'error' } });
或者在您的pug
模板中,作为一级成员访问它,例如:
#error.pug
extends layout
block content
h1= message
h2= status
pre #{stack}
推荐阅读
- embed - 他们是如何通过 youtube 做到这一点的
- laravel - 当'to'未被覆盖时,Laravel 电子邮件发送不起作用
- python - 通过 rs485 到 Arduino 的 RPi 未接收到所有字符
- android - 如何使用 API 26 或更高版本访问 android 中的帐户名称?
- php - PHP 中的服务器端电子邮件已存在验证
- javascript - 与提示和警报混淆
- logging - logger.getAppender 在哪里(从 log4j 迁移到 slf4j+log4j)
- python - 在 Python 3 中将多个条目解压缩为“字段”的字符串
- coldfusion - Twilio - 在漫长的过程中播放音乐
- ios - 在 Swift 中使用 DispatchQueue 进行同步处理