node跳转404.html,node.js – 如何重定向404错误到ExpressJS中的页面?

我发现这个例子很有帮助:

所以它实际上是这部分:

// "app.router" positions our routes

// above the middleware defined below,

// this means that Express will attempt

// to match & call routes _before_ continuing

// on, at which point we assume it's a 404 because

// no route has handled the request.

app.use(app.router);

// Since this is the last non-error-handling

// middleware use()d, we assume 404, as nothing else

// responded.

// $ curl http://localhost:3000/notfound

// $ curl http://localhost:3000/notfound -H "Accept: application/json"

// $ curl http://localhost:3000/notfound -H "Accept: text/plain"

app.use(function(req, res, next){

res.status(404);

// respond with html page

if (req.accepts('html')) {

res.render('404', { url: req.url });

return;

}

// respond with json

if (req.accepts('json')) {

res.send({ error: 'Not found' });

return;

}

// default to plain-text. send()

res.type('txt').send('Not found');

});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值