【问题标题】:How to display "404 not found" in Node.js if I input a wrong route?如果我输入错误的路线,如何在 Node.js 中显示“404 not found”?
【发布时间】:2020-08-05 02:53:52
【问题描述】:

我在这里遇到了一个小问题。如果我输入了错误的路线,我想显示404 not found

如果我转到http://localhost:3000,下面的代码只会显示404 not found/

但是当我输入http://localhost:3000/wrongroute 时,它会显示Cannot GET /wrongroute 而不是 404 not found.

const bodyParser = require("body-parser");
const mysql = require('mysql');
const router = express.Router();

const db = mysql.createConnection({
    host: 'xxx.xx.xx.xx',
    user: 'root',
    password: '12345',
    database: 'test'
});

db.connect((err) =>{
    if(err){
        throw err;
    }
    console.log('Mysql Connected');
    // res.send("Mysql Connected");
});

router.post('/login', function (req, res) {
      res.send("This is from login route");
   res.end();
})

router.post('/signup', function (req, res) {
   res.send("This is from signup route");
   res.end();
})

router.get('/', function(req, res){
 res.send("404 not found");
});


module.exports = router;

【问题讨论】:

标签: javascript node.js


【解决方案1】:

在 END 处添加这条路线。

router.get("*", (_, res) => res.status(404).send("404 not found"))

【讨论】:

    【解决方案2】:

    这是您的解决方案。请记住将后备路由放在端点列表的末尾。

    router.post('/your-route', function (req, res) {
       ...
    });
    
    router.post('/another-route', function (req, res) {
       ...
    });
    
    router.get('*', function(req, res) {
      // This is a fallback, in case of no matching
    
      res.status(404);
      res.send('Not found.');
    });
    

    【讨论】:

      猜你喜欢
      • 2021-12-31
      • 1970-01-01
      • 2013-06-18
      • 2016-06-01
      • 2020-12-24
      • 2015-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多