Mercer
Mercer

Reputation: 9986

Can't set header after they sent

My code:

function tokenReceived(response, error, token) {
  if (error) {
    console.log("Access token error: ", error.message);
    response.writeHead(200, {"Content-Type": "text/html"});
    response.write('<p>ERROR: ' + error + '</p>');
    response.end();
  }
  else {
 var cookies = ['node-tutorial-token=' + token.token.access_token + ';Max-Age=3600',
                   '[email protected];Max-Age=3600'];
                   console.log("cookies: ", cookies);
    response.setHeader('Set-Cookie', cookies);
    response.writeHead(200, {"Content-Type": "text/html"});
    response.write('<p>Access token saved in cookie.</p>');
    response.end();
  }
}

My error:

Error: Can't set headers after they are sent. at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11) at tokenReceived (D:\node-tutorial\index.js:47:14) at D:\node-tutorial\authHelper.js:41:9 at tryCatcher (D:\node-tutorial\node_modules\bluebird\js\main\util.js:26:23) at Promise.successAdapter (D:\node-tutorial\node_modules\bluebird\js\main\nodeify.js:23:30) at Promise._settlePromiseAt (D:\node-tutorial\node_modules\bluebird\js\main\promise.js:579:21) at Promise._settlePromises (D:\node-tutorial\node_modules\bluebird\js\main\promise.js:697:14) at Async._drainQueue (D:\node-tutorial\node_modules\bluebird\js\main\async.js:123:16) at Async._drainQueues (D:\node-tutorial\node_modules\bluebird\js\main\async.js:133:10) at Immediate.Async.drainQueues [as _onImmediate] (D:\node-tutorial\node_modules\bluebird\js\main\async.js:15:14) at processImmediate [as _immediateCallback] (timers.js:383:17)

Upvotes: 0

Views: 780

Answers (3)

FF_Dev
FF_Dev

Reputation: 578

Both response.setHeader() and response.writeHead() write (and commit) headers.

Your should either do

response.statusCode = 200;
response.setHeader('Content-Type', 'text/html');
response.setHeader('Set-Cookie', cookies);

Or

response.writeHead(200, {
    'Content-Type': 'text/html',
    'Set-Cookie': cookies
});

Upvotes: 1

Zeeshan Hassan Memon
Zeeshan Hassan Memon

Reputation: 8325

response.setHeader is only to set a singular header.

response.writeHead is to set multiple headers.

Try this way:

   response.writeHead(200, {
        "Content-Type": "text/html",
        "Set-Cookie": cookies
    });

Upvotes: 1

Simone Bongiovanni
Simone Bongiovanni

Reputation: 31

This issues is beacuse you sent response two times(the first time with writeHead and second time with write). Try to use response.status(200).send(data)

Upvotes: -2

Related Questions