Node.js gives error: Can't set headers after they are sent

Node.js gives error: Can't set headers after they are sent

我是 node.js 的新手,我正在执行从 Gmail 中获取所有电子邮件地址的功能。收到回复后,我将回复发送到 jade 模板中。获得单一响应后,我在终端中收到错误消息:

Error: Can't set headers after they are sent.

我的代码如下:

module.exports.getmailist =  function(req , res) {

    var google = require('googleapis');
    var gmail = google.gmail('v1');
    var email_list = Array();
    var myObject = Array();
    var accounting = [];
    var messageIds = [];
    var jsonString = false;
    var employees = {};
    var OAuth2 = google.auth.OAuth2;
    var oauth2Client = new OAuth2("--MY CLIENT ID--","SECRET ID","REDIRECT URL");
    oauth2Client.credentials = { access_token: req.session.access_token};

    var addData = function (req,response) {
        console.log(response);
        res.render('getmailist',{title: 'Product Template', result: response});
    }

    gmail.users.messages.list({ userId: 'me', 'q': "inbox", auth: oauth2Client}, function(err, response) {
        for(var i = 0; i< response.messages.length; i++) {
            //console.log(response.messages[i].id);
            gmail.users.messages.get({ userId: 'me', id:response.messages[i].id , auth: oauth2Client}, function(error , resp) {

            if(resp != "")
            {
                addData(req,resp)
            }
        });
    }

    return true;
    });
};

console.log(response) 中,我首先获取电子邮件的数据值作为对象,然后显示以下错误。

Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (http.js:690:11)
at ServerResponse.header (/var/www/nodegoogle/node_modules/express/lib/response.js:700:10)
at ServerResponse.send (/var/www/nodegoogle/node_modules/express/lib/response.js:154:12)
at fn (/var/www/nodegoogle/node_modules/express/lib/response.js:934:10)
at View.exports.renderFile [as engine] (/var/www/nodegoogle/node_modules/jade/lib/index.js:374:12)
at View.render (/var/www/nodegoogle/node_modules/express/lib/view.js:93:8)
at EventEmitter.app.render (/var/www/nodegoogle/node_modules/express/lib/application.js:566:10)
at ServerResponse.res.render (/var/www/nodegoogle/node_modules/express/lib/response.js:938:7)
at addData (/var/www/nodegoogle/lib/callbacks/routes.js:63:11)
at /var/www/nodegoogle/lib/callbacks/routes.js:74:13

您收到此错误是因为到达 addData(req,resp) 的迭代的第一步是发送响应。请记住:render 方法结束响应。

如果您想遍历 response.messages 数组并在发送响应之前对每个项目执行操作,您必须确保仅在循环结束后调用 addDate(req,res)

看看 async.each from the async 模块。文档中的示例:

async.each(openFiles, function( file, callback) {

  // Perform operation on file here. 
  console.log('Processing file ' + file);

  if( file.length > 32 ) {
    console.log('This file name is too long');
    callback('File name too long');
  } else {
    // Do work to process file here 
    console.log('File processed');
    callback();
  }
  }, function(err){
    // if any of the file processing produced an error, err would equal that error 
    if( err ) {
      // One of the iterations produced an error. 
      // All processing will now stop. 
      console.log('A file failed to process');
    } else {
      console.log('All files have been processed successfully');
    }
});

因此,在您的场景中,您只需在每个项目上完成您的工作(当然,在每个项目之后调用本地 callback)并在最后一次回调时调用您的 addData(req,resp) .