我有一种奇怪的情况......
我有一个Express.js,Node.js和Mongoose网络应用程序。
其中一条路由有一个调用respond.send(...)的猫鼬回调。但是,因为回调后没有别的东西,我怀疑它会自动转到next()路由。
例如:
//getItem
app.get('/api/ItemOne', isUserValid, routes.getItem);
//getAnotherItem
app.get('/api/getAnotherItem', isUserValid, routes.getAnotherItem);
//Routes
exports.getItem = function (req, res) {
//console.log ('In getItem');
getItem .findOne({ some_id : some_id}, function(err, getItem ){
//console.log ('In getItem callback');
res.send({
itemName : getItem .itemName,
itemValue : getItem .itemValue;
});
})
});
exports.getAnotherItem = function (req, res) {
//console.log ('In getAnotherItem');
getAnotherItem.findOne({ some_id : some_id}, function(err, getAnotherItemRet){
//console.log ('In getAnotherItem Callback');
res.send({
itemName : getAnotherItemRet.itemName,
itemValue : getAnotherItemRet.itemValue;
});
})
});
我在控制台上收到以下消息序列......
In getItem
In getAnotherItem
In getItem callback
In getAnotherItem callback
我假设因为路线没有完成,它会自动调用next()。
问:如何防止自动调用第二条路线。
答案 0 :(得分:4)
尝试撤消req
和res
:
// wrong
exports.getItem = function (res, req) {
// right
exports.getItem = function (req, res) {
(和getAnotherItem
相同)。
答案 1 :(得分:2)
为了理解您为什么按顺序获取消息,我们需要知道您要调用哪个URL来生成该消息。
无论如何,“/ api / getItem”没有调用“/ api / getAnotherItem”有两个原因:
你可能有某种中间件(I.E.与app.use一起使用而不是app.get)可以调用类似的东西,但最有可能的是,你在某种程度上同时调用这两个URL。