I’m beginning under NodeJS/Express and I’m facing the following problem (I probably didn’t get all the tricks of async programming yet)
I’ve made a middleware in charge of checking if a oauth_token paramters is passed (actually implementing oAuth layer on my node server)
I’m doing this :
function myMiddle(req,res,next) {
var oAuthToken = req.query["oauth_token"];
if (oAuthToken == undefined) {
res.send(406);
res.end();
next(new Error('No token provided'));
}
/* Basically doing some DB stuff with MongoDB, connecting and using oAuthToken provided to query, etc.. */
The thing is that I expected the code to “die” when he doesn’t receive the oauth_token parameters in the query string. It’s actually raising me an error and returning greatly 406 error to my HTTP client, but code keeps processing behind and raises me mutable headers errors caused by my processing code after, and my script dies.
Something I’m missing? Thanks by advance.
If your
oAuthTokenis undefined Node.js makes a response. After that you firenext(...)which tries to make another response to the same request. This fails and you see what you see. Note that in Node.js usingres.send();andres.end();does not stop your function. So what you need is to do the following:or do it the other way – use
res.send(406); res.end();withoutnext(...).