1

我在 app.js 的底部使用了这段代码

app.use(function (req, res) {
   res.send('Route Not Found');
})

但它在每个请求中执行。我只想在找不到路由时执行它。

4

2 回答 2

2

这工作正常。如果您包含外部路由文件,请确保将路由放在app.get('*' ... 每个文件的末尾。

const express = require('express')
const app = express()

app.get('/', function(req, res){
        res.status(200).send('GET /')
})

app.get('/a', function(req, res){
        res.status(200).send('GET /a')
})

app.get('*', function(req, res){
        res.status(404).send('404')
})

app.listen(3000)
于 2018-09-14T05:24:01.213 回答
1

将您的路线处理程序放在之前:

app.get("/a", require("./controllers/handler1.js"); // catch get route on a
app.get("/b", require("./controllers/handler2.js"); // catch get route on b
app.post("/a", require("./controllers/handler1.js"); // catch post route on a

// error handler, if no route has been caught
app.get("/*", function(req, res){ res.send("404 not found"); res.end();});
app.post("/*", function(req, res){ res.send("404 not found"); res.end();});
于 2018-09-13T11:59:27.630 回答