Jim M
Jim M

Reputation: 351

Can't set headers

I have some basic authentication in a route that when used is throwing a console error.

Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:356:11)
    at ServerResponse.header

It only occurs when the "if" statement is true (the code within the if statement runs). When that doesn't run, I am not getting any error and the "home" view renders without error.

routes.get('/scan', (req, res, next) => {
    const orderID = req.query.order;
    const token   = req.query.token;

    if (!hasAccess(token))
        res.status(401).send('Unauthorized');

    res.render('home', {order});
});

Upvotes: 1

Views: 200

Answers (2)

boehm_s
boehm_s

Reputation: 5534

This error is thrown when you try to respond more than one time to your request.

To avoid this kind of error, you should return when sending a response, so the function will not continue.

In your case :

routes.get('/scan',  (req, res, next) => {
  const orderID = req.query.order;
  const token   = req.query.token;

  if( !hasAccess( token ) )
    return res.status(401).send('Unauthorized');
  return res.render('home', {order});
});

Upvotes: 2

mscdex
mscdex

Reputation: 106698

You should add a return; after your res.status(401).send('Unauthorized'); to avoid sending a duplicate response.

Upvotes: 1

Related Questions