0

我使用 passport-google-oauth 进行身份验证和node-gmail-api获取 gmail !所以我想在经过身份验证后显示 gmail 消息,以便我这样编码routes.js

app.get('/profile', isLoggedIn, function(req, res) {
      var gmail = new Gmail(req.user.google.token)
      , s = gmail.messages('label:inbox', {max: 10}),mm;

    s.on('data', function (d) {
       res.render('profile.ejs', {
            user : req.user, // get the user out of session and pass to template,
            mm: d.snippet,
            layout: 'header'
        });
    })

关于代码可以获取 gmail 消息但出现如下错误并停止节点服务器运行

错误:发送后无法设置标头。
在 validateHeader (_http_outgoing.js:494:11)
在 ServerResponse.setHeader (_http_outgoing.js:501:3)
.....

res.render如果我在函数之外编写s.on('data'),则无法在 render 中传递邮件片段字符串。如何使用node-gmail-apimessage 正确呈现?

4

1 回答 1

0

我得到了@Freddy对gitter.im的建议的解决,s.on('data')是管道/流式传输数据,我得到的第一个结果不一定是最终/最终结果类似于等待最后一个stream.on中异步函数的回调( 'data') 事件应该走上正轨所以,我需要等待 s.on('data') 中的所有数据完成,然后再尝试运行 res.render()

  var data

  stream.on('data', function (d) {
    data = d
  })

  stream.on('end', function () {
    t.equal(data.id, '147dae72a4bab6b4')
    t.equal(data.historyId, '6435511')
    t.equal(data.messages.length, 1)
    t.equal(data.messages[0].snippet, 'This is a test email.')
    t.equal(stream.resultSizeEstimate, 1)
    t.end()
  })
})

在上述情况下,数据被收集并存储在数据变量中,然后我才能在最终流中使用它。stream.on( 'end'是我应该把res.render放在下面的地方......

app.get('/profile', isLoggedIn, function(req, res) {
      var gmail = new Gmail(req.user.google.token)
      , s = gmail.messages('label:inbox', {max: 10}),data;

    s.on('data', function (d) {
       data = d;
    })
    s.on('end', function () {
      res.render('profile.ejs', {
            user : req.user, // get the user out of session and pass to template,
            mm: data.snippet,
            layout: 'header'
        });
    });
于 2018-04-02T07:43:22.643 回答