0
module.exports = function(app) {
    try{
         app.get('/:path/:id', function (req, res) {
           res.render(req.params.path+'/'+req.params.id, { id: req.params.id });
         }); 

    }
    catch(e){
         console.error(e);
    }
};

如果未找到 res.render 页面,如何重定向到另一个页面?

4

2 回答 2

1

404最简单的方法是在模板渲染中发生错误时重定向到您的路线。

喜欢

app.get('/:path/:id', function (req, res) {

   res.render(req.params.path+'/'+req.params.id,{id:req.params.id},function(err,html){
        if(err) {
            //error in rendering template o redirect to 404 page
            res.redirect('/404');
        } else {
            res.end(html);
        }
   });

});

参考帖子: 如何使用 express.js 在 node.js 中捕获渲染错误/缺少模板?

于 2013-11-01T07:25:17.783 回答
0

为什么不创建一个处理 404 页面的函数。即是这样的:

var show404Page = function(res) {
    var html = "404 page";
    res.end(html);
}
module.exports = function(app) {
    try{
         app.get('/:path/:id', function (req, res) {
            res.render(req.params.path+'/'+req.params.id, { id: req.params.id });
         }); 
    }
    catch(e){
        console.error(e);
        show404Page(res);
    }
};
于 2013-11-01T07:48:28.603 回答