mtanton mtanton - 5 months ago 24
Node.js Question

Error: Can't set headers after they are sent on page refresh

When I try to refresh a particular page, I get Error: Can't set headers after they are sent. Now, when I actually click a link to that page, it doesn't happen. I've looked through the chain of events during a request thoroughly. The middleware and request doesn't seem to be causing res.end() to be called twice.

Middleware being called on every request:

projectRouter.use(function(req, res, next) {
var token = req.body.token || req.params.token || req.headers['x-access-token'];

console.log(token);

if (token) {
jwt.verify(token, superSecret, function(err, decoded) {
if (err) {
res.status(403).send({
success: false,
message: 'Failed to authenticate token.'
});
} else {
req.decoded = decoded;

next();
}
});
} else {
res.status(403).send({
success: false,
message: 'No token provided'
});
next();
}
});


Request error is happening on:

projectRouter.route('/projects/:proj_id')

.get(function(req, res) {
Project.findById(req.params.proj_id, function(err, project) {
if (err) { res.send(err); return; }

res.json(project);
});
})


I am using angular on the front end and am using an interceptor to write a user token to x-access-token. So when this error happens, the middleware fails to get the token, causing a 403 on that page. I've been trying to figure this out for a couple of days and am at a loss. I imagine it something really dumb though.

Answer
} else {
  res.status(403).send({
    success: false,
    message: 'No token provided'
  });
  next();
}

Your else block is sending a response and also calling next(), which means that it will send an error and also try to run your route and send a response. Since both are trying to send a response, you'll get an error.