【发布时间】:2017-04-13 21:11:38
【问题描述】:
我有一个这样的中间件
// route middleware to verify a token
app.use(function(req, res, next) {
console.log(req.baseUrl);
// check header or url parameters or post parameters for token
var token = req.body.token || req.query.token || req.headers['x-access-token'];
// decode token
if (token) {
// verifies secret and checks exp
jwt.verify(token, app.get('superSecret'), function(err, decoded) {
if (err) {
return res.json({
success: false,
message: 'Failed to authenticate token.'
});
} else {
// if everything is good, save to request for use in other routes
req.decoded = decoded;
next();
}
});
} else {
// if there is no token
// return an error
return res.status(403).send({
success: false,
message: 'No token provided.'
});
}
});
这条路线 http://localhost:8080/verifyAccount 不响应为 No token provided
app.get('/verifyAccount', function (req, res) {
res.json({ message: 'Welcome to verify account!' });
});
但以下路线 http://localhost:8080/verifyAccount?id=123 可以:
app.get('/verifyAccount/:id', function (req, res) {
res.json({ message: 'Welcome to verify account!' });
});
中间件代码在代码文件底部,获取路径在上
背后的概念是什么?
为什么添加 get 参数会强制执行中间件?
刚刚发现如果我这样称呼它http://localhost:8080/verifyAccount/id=123,它会正确返回Welcome to verify account!
【问题讨论】:
-
我已经设置了一个非常基本的示例(只为每个路由和中间件提供 console.log 输出)。我可以看到从未调用过中间件。只有当请求“滴”到它的未知路由时才会调用它。您的代码一定有其他问题。
-
啊,你的错误。带有查询参数
?id=123的请求与/:id不匹配。应该是verifyAccount/123 -
@devnull69 如果我的参数名称是
p1那么我将如何称呼它? -
同理。位置决定参数,而不是名称。该名称仅在您的节点代码中用于引用参数
-
你会有多个像
verifyAccount/:id/:otherParameter这样的斜杠,可以使用verifyAccount/123/234调用
标签: javascript node.js express middleware