I have a weird situation...
I have a Express.js, Node.js and Mongoose web app.
One of the routes has a mongoose callback that calls respond.send(...). However, because there is nothing else after the callback, I suspect it goes to next() route automatically.
Ex:
//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;
});
})
});
I get the following sequence of messages on the console...
In getItem
In getAnotherItem
In getItem callback
In getAnotherItem callback
I am assuming because the route does not finish, it calls next() automatically.
Q: How do I prevent the second route from being called automatically.
Try reversing req
and res
:
// wrong
exports.getItem = function (res, req) {
// right
exports.getItem = function (req, res) {
(and same for getAnotherItem
).
In order to understand why you get messages in that order, we need to know what url are you calling to generate that message.
In any case though, "/api/getItem" does not call "/api/getAnotherItem" for two reasons:
It's possible you have some kind of middleware (I.E. used with app.use and not app.get) which could call something like that, but most likely, you are calling both urls at the same time somehow.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With