kingpin
kingpin

Reputation: 1498

Nodejs/Express POST request middleware unable to call next() in callback

There is very strange behavior in Express, can't figure out, mind cracking problem.

So suppose in req.user I have user id and here is my middleware code.

app.use(function(req, res, next){
  var User = mongoose.model('User');
  User.findById(req.user, function(err, user){
    if(err) return next(err);
    res.locals.user = user;
    console.log(user);
    next(); 
  });
}

So it is working just fine when request type is GET, but if request is POST it just get to infinite waiting, until I receive No data received.

There is no issues with database nor with session: console.log(user) always works.

This is very very strange... I even tried to use another async function and it didn't work again for POST only requests.

fs.stat(__dirname + '/schemas/user.js', function(err, stat){
  next();
})

My conclusion is that if next() is being called from callback during POST request it just hangs, but who can explain me WHY???

The original issue that brings me here was when I was trying to use passport.js deserializer which reads user from mongodb for every request, so that fails too for POST only requests.

configurations

{
  "name": "myApp",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "./node_modules/.bin/nodemon app.js"
  },
  "dependencies": {
    "express": "3.0.0rc5", //did also tried with rc4
    "ejs": ">= 0.8.3",
    "express-partials": "latest",
    "mongodb": ">= 1.1.7",
    "mongoose": "*",
    "node-uuid": "*",
    "passport": "*",
    "passport-local": "*",
    "flashify": "*",
    "nodemon": "latest"
  }
}

express configuration

var app = express();
app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'ejs');
  app.use(express.logger('dev'));
  app.use(partials());
  app.use(express.cookieParser('Secret secret'));
  app.use(express.session());
  app.use(passport.initialize());
  app.use(passport.session());

  app.use(MY_MIDDLEWARE_HERE);

  app.use(express.favicon());  
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(flashify);
  app.use(app.router);
  app.use(express.static(path.join(__dirname, 'public')));
});


app.configure('development', function(){
  app.use(express.errorHandler());
});

Upvotes: 1

Views: 2113

Answers (1)

Jared Hanson
Jared Hanson

Reputation: 16000

I'm not sure this will have an effect, but its recommended to use bodyParser middleware earlier in the middleware stack. I would put it below cookieParser and above passport middleware, since many authentication mechanisms need to find parameters in the body.

Upvotes: 4

Related Questions