错误:将标头发送到客户端后无法设置标头

时间:2019-06-08 16:44:43

标签: node.js express

我编码Promise.all,它在运行时从db加载大约20行,它停止了

我的代码

router.get('/', (req, res) => {
  var cat = res.locals.lcCategories;

Promise.all([postModel.getTop10View(),postModel.getTop10latest()]).then(data => {
    console.log(data);
    return res.render('home');
  }).catch(next);

});

错误:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:470:11)
    at ServerResponse.header (C:\Users\tranh\Desktop\Web2-News\node_modules\express\lib\response.js:767:10)
    at ServerResponse.send (C:\Users\tranh\Desktop\Web2-News\node_modules\express\lib\response.js:170:12)
    at done (C:\Users\tranh\Desktop\Web2-News\node_modules\express\lib\response.js:1004:10)
    at Immediate.<anonymous> (C:\Users\tranh\Desktop\Web2-News\node_modules\express-handlebars\lib\utils.js:26:13)
    at runCallback (timers.js:705:18)
    at tryOnImmediate (timers.js:676:5)
    at processImmediate (timers.js:658:5)

enter image description here

1 个答案:

答案 0 :(得分:0)

我有同样的问题,当您的api已经发送响应时,基本上会发生此错误,但是由于nodejs的异步能力或丢失的周期,它再次发送了响应,我认为promise.all已运行并且请求仍然存在发送,并且当promise.all从其循环返回时,它再次发送一个请求。 在promise.all之前使用await 像

await Promise.all([postModel.getTop10View(),postModel.getTop10latest()]).then(data => {
        console.log(data);
        return res.render('home');
      }).catch(next);