发送后无法设置标头

时间:2016-03-08 14:19:03

标签: javascript node.js asynchronous

我的代码:

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',
                   'node-tutorial-email=xxxx@xxx.xx;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();
  }
}

我的错误:

  

错误:发送后无法设置标头。       在ServerResponse.OutgoingMessage.setHeader(_http_outgoing.js:344:11)       at tokenReceived(D:\ node-tutorial \ index.js:47:14)       在D:\ node-tutorial \ authHelper.js:41:9       在tryCatcher(D:\ node-tutorial \ node_modules \ bluebird \ js \ main \ util.js:26:23)       在Promise.successAdapter(D:\ node-tutorial \ node_modules \ bluebird \ js \ main \ nodeify.js:23:30)       在Promise._settlePromiseAt(D:\ node-tutorial \ node_modules \ bluebird \ js \ main \ promise.js:579:21)       在Promise._settlePromises(D:\ node-tutorial \ node_modules \ bluebird \ js \ main \ promise.js:697:14)       在Async._drainQueue(D:\ node-tutorial \ node_modules \ bluebird \ js \ main \ async.js:123:16)       在Async._drainQueues(D:\ node-tutorial \ node_modules \ bluebird \ js \ main \ async.js:133:10)       在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)

3 个答案:

答案 0 :(得分:1)

response.setHeader只是设置一个单一的标题。

response.writeHead是设置多个标头。

尝试这种方式:

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

答案 1 :(得分:1)

response.setHeader()response.writeHead()写入(和提交)标头。

你应该做

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

或者

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

答案 2 :(得分:-2)

这个问题是因为您发送了两次响应(第一次使用writeHead,第二次使用write)。尝试使用response.status(200).send(data)