我不知道这样做的函数,有人知道吗?


当前回答

上面的代码对我不起作用。

所以我找到了一个真正有效的新解决方案!

app.use(function(req, res, next) {
    res.status(404).send('Unable to find the requested resource!');
});

或者您甚至可以将其呈现到404页面。

app.use(function(req, res, next) {
    res.status(404).render("404page");
});

希望这对你有所帮助!

其他回答

你可以把一个中间件放在最后一个位置,它会抛出一个NotFound错误, 甚至直接渲染404页面:

app.use(function(req,res){
    res.status(404).render('404.jade');
});

如果你想从你的函数(路由)重定向到错误页面,那么做以下事情-

Add general error messages code in your app.js - app.use(function(err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message res.locals.error = req.app.get('env') === 'development' ? err : {} // render the error page // you can also serve different error pages // for example sake, I am just responding with simple error messages res.status(err.status || 500) if(err.status === 403){ return res.send('Action forbidden!'); } if(err.status === 404){ return res.send('Page not found!'); } // when status is 500, error handler if(err.status === 500) { return res.send('Server error occured!'); } res.render('error') }) In your function, instead of using a error-page redirect you can use set the error status first and then use next() for the code flow to go through above code - if(FOUND){ ... }else{ // redirecting to general error page // any error code can be used (provided you have handled its error response) res.status(404) // calling next() will make the control to go call the step 1. error code // it will return the error response according to the error code given (provided you have handled its error response) next() }

如果您使用express-generator包:

下(err);

这段代码将您发送到404中间件。

app.get('*',function(req,res){
 res.redirect('/login');
});

上面的代码对我不起作用。

所以我找到了一个真正有效的新解决方案!

app.use(function(req, res, next) {
    res.status(404).send('Unable to find the requested resource!');
});

或者您甚至可以将其呈现到404页面。

app.use(function(req, res, next) {
    res.status(404).render("404page");
});

希望这对你有所帮助!