你好,我在这里有一个小问题,我要显示的是如果输入错误的路线,则找不到“ 404”。
如果我转到http://localhost:3000/,下面的代码仅显示“ 404 not found”但是当我输入http://localhost:3000/wrongroute时,它显示“无法获取/错误的路线”我要显示的是“找不到404”,谢谢。
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;
在END添加此路线。
router.get("*", (_, res) => res.status(404).send("404 not found"))
这是您的解决方案。请记住将后备路由放置在端点列表的末尾。
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.');
});