Afraz Ahmad Afraz Ahmad - 1 year ago 59
Node.js Question

Async response - can't set headers after they are sent

I am new to Node.js programming. I am having a big trouble as I keep getting same error in the following code. I can not understand what is the problem there.

Can't set headers after they are sent.

var mongoose = require('mongoose');

module.exports = function(req, res) {
var User = require('../../Schema/User');
User.count({ $and: [{ "username": req.body.username }, { "password": req.body.password }] },
function(err, count) {

Answer Source

You are calling next() in your route code essentially turning your login snippet into middleware and passing it down. You are getting this error because in your login code you are outputting with res.json and then still calling the next step with next. l.

Your issue is just that headers must come before any output. Whether you write or pass the data on in your middleware is up to you as long as you are aware of subsequent possible headers/writes.

But you may want to reconsider your setup - in general auth middleware would be used to verify that a user is logged on - perhaps checking a session cookie. If the user is ok then you can fetch (if needed) user data based on the cookie info (i.e. the _id) or redirect the user to a login page.

What you have here is the login route which doesnt really need middleware. Simply check if user is valid and either set a session cookie or tell them it's a no go.

Passport makes things easier. Check out this post. The underlying principle is the same I outlined above, it just makes it easier to get going.