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


当前回答

我在定义所有路由后所做的是捕捉潜在的404并转发到错误处理程序,如下所示:

    const httpError = require('http-errors');

    ...

    // API router
    app.use('/api/', routes);
    
    // catch 404 and forward to error handler
    app.use((req, res, next) => {
      const err = new httpError(404)
      return next(err);
    });

    module.exports = app;

其他回答

发送到自定义页面:

app.get('*', function(req, res){
  if (req.accepts('html')) {
     res.send('404', '<script>location.href = "/the-404-page.html";</script>');
     return;
  }
});

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

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

如果您使用express-generator包:

下(err);

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

https://github.com/robrighter/node-boilerplate/blob/master/templates/app/server.js

这就是node-boilerplate所做的。

在某些情况下,404页面不能被写入并作为最后一个路由执行,特别是如果您有一个异步路由功能,从而引入了一个迟到的/路由。在这些情况下可以采用下面的模式。

var express = require("express.io"),
    app = express(),
    router = express.Router();

router.get("/hello", function (req, res) {
    res.send("Hello World");
});

// Router is up here.
app.use(router);

app.use(function(req, res) {
    res.send("Crime Scene 404. Do not repeat");
});

router.get("/late", function (req, res) {
    res.send("Its OK to come late");
});

app.listen(8080, function (){
    console.log("Ready");
});