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


当前回答

这种方法更简单,但它必须是所有路线之后的最后一件事。

app.use( (req, res) => {
    //render page not found 
    res.render('404')
})

其他回答

// Add this middleware
// error handler
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
   res.status(err.status || 500);
   res.render('error');
  });

覆盖express中的所有HTTP动词

为了覆盖所有HTTP动词和所有剩余路径,您可以使用:

app.all('*', cb)

最终的解决方案是这样的:

app.all('*', (req, res) =>{
    res.status(404).json({
        success: false,
        data: '404'
    })
})

你不应该忘记把路由器放在最后。 因为路由器的顺序很重要。

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

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

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");
});

希望这对你有所帮助!

在app.js的最后一行放入这个函数。这将覆盖默认的page-not-found错误页面:

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

它将覆盖没有有效处理程序的所有请求,并呈现您自己的错误页面。

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

https://github.com/visionmedia/express/blob/master/examples/error-pages/index.js

所以,它实际上是这一部分:

// "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.json({ error: 'Not found' });
    return;
  }

  // default to plain-text. send()
  res.type('txt').send('Not found');
});