express - 为什么 app.use 之后定义的路由在获取请求后没有返回任何内容?
问题描述
我是 node.js 和 express.js 的新手,我正在练习服务器创建的基础知识。我发现如果我在 app.use 之后编写 app.get,那么该代码根本不起作用。
我尝试用谷歌搜索“为什么 app.use express.js 404”的各种组合,但一无所获。
const express = require('express');
const app = express();
// 1) Add a route that answers to all request types
app.route('/article')
.get(function(req, res) {
res.send('Get the article');
})
.post(function(req, res) {
res.send('Add an article');
})
.put(function(req, res) {
res.send('Update the article');
});
// on the request to root (localhost:3000/)
app.get('/', function (req, res) {
res.send('<b>My</b> first express http server');
});
// 3) Use regular expressions in routes
// responds to : batmobile, batwing, batcave, batarang
app.get(/bat/, function(req, res) {
res.send('/bat/');
});
// 2) Use a wildcard for a route
// answers to : theANYman, thebatman, thesuperman
app.get('/the*man', function(req, res) {
res.send('the*man');
});
// app.get does NOT return anything thats defined beyond this method call
app.use(function(req, res, next) {
res.status(404).send("Sorry, that route doesn't exist. Have a nice day :)");
});
// this will not be work unless moved above app.use
app.get('/welcome', function (req, res) {
res.send('<b>Hello</b> welcome to my http server made with express');
});
app.listen(3000, function () {
console.log('Example app listening on port 3000.');
});
解决方案
路由处理程序按照定义的顺序检查路径匹配。
一旦你定义了这个:
app.use(function(req, res, next) {
res.status(404).send("Sorry, that route doesn't exist. Have a nice day :)");
});
响应已发送且next()
尚未被调用,因此不会调用链中的更多路由处理程序。
您的 404 路由处理程序应该是最后定义的路由处理程序。这个想法是,如果没有其他路由处理程序处理过此请求,那么您一定没有,并且它必须是您应该返回 404 的路由。但是,您只能知道,如果您将这个请求放在链中的最后一个(因此将其定义在最后,因此它将在链中的最后一个),则没有其他路由处理程序将处理此请求。
多解释一点,每次你这样做app.use()
,app.post()
或app.get()
该系列中的任何其他人时,它都会向内部路由数组添加一个路由处理程序,并按照代码运行的顺序将它们添加到该数组中。第一个注册路由位于数组的开头,最后一个位于数组的末尾。
当一个请求进来时,Express 从该数组的开头开始并寻找第一个匹配传入请求的路径和类型的处理程序并调用该路由处理程序。
如果该路由处理程序从不调用next()
,则不再为该请求调用路由处理程序。完成。如果该路由处理程序调用,next()
那么 Express 将继续在数组中查找下一个匹配的路由处理程序。
因此,您可以看到您的app.use()
404 处理程序从不调用next()
,因此 Express 将永远不会继续为该请求寻找更多匹配的路由处理程序,因此在此之后声明的路由处理程序永远不会找到并且永远不会被调用。
推荐阅读
- c# - Microsoft Graph API 将参与者角色分配给在线会议
- numerical-methods - 什么时候应该开始将二次方程视为数值求根中的线性?
- angular - 具有两个公钥的 Angular Stripe 实现取决于帐户类型
- c++ - 使用空标签结构,编译器声称我缺少初始化程序,但我不是
- c++ - 零初始化忽略构造函数
- mysql - Sql 查询打印所有部门名称和该部门最新员工的姓名
- reactjs - 反应状态没有在 SetInterval 方法中正确更新
- wpf - WPF 和 UWP ,与早期窗口的兼容性
- algorithm - 面试题:如果新增的区间会和区间列表中的K个区间重叠
- python - 如何在 numba 预编译函数中使用 struct.unpack