【问题标题】:Can't figure out why I keep getting [ERR_HTTP_HEADERS_SENT] error无法弄清楚为什么我不断收到 [ERR_HTTP_HEADERS_SENT] 错误
【发布时间】:2019-10-09 05:12:26
【问题描述】:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

我看过其他关于同一问题的帖子,但我无法弄清楚如何解决我的问题。我有代码处理这样的发布请求:

router.post('/', function(req, res) {
  var movies = JSON.parse(fs.readFileSync('movies.json'));
  var title = req.body.title;
  movies.forEach(function(movie) {
    if (title == movie.title) {
      return res.render('movie', { watched: false });
    } else {
      return res.render('movie', { watched: true });
    }
  });
});

我知道问题是由于 res.render() 出现两次,但即使有 return 声明,它仍然给我同样的错误,所以我很难理解它是如何被发送两次的。由于return 关键字,它不应该只发送一次吗?

另外,如果我像这样修改我的代码:

router.post('/', function(req, res) {
  var movies = JSON.parse(fs.readFileSync('movies.json'));
  var title = req.body.title;
  movies.forEach(function(movie) {
    if (title == movie.title) {
      return res.render('movie', { watched: false });
    }
  });
res.render('movie', { watched: true});
});

然后我只在 if 语句为假时收到错误。为什么会这样?

【问题讨论】:

    标签: javascript node.js express http-headers


    【解决方案1】:

    你正在返回内部 for 循环,所以每次它都会发送

    如下修改你的代码

    router.post('/', function(req, res) {
      var movies = JSON.parse(fs.readFileSync('movies.json'));
      var title = req.body.title;
      var counter =0;
      var arr = [];
      movies.forEach(function(movie) {
        if (title == movie.title) {
          arr.push({ watched: false , movieId:id})      
        } else {
          arr.push({ watched: true , movieId:id})
        }
        counter++;
       if(counter == movies.length){
          return res.send({'movie':arr});
       }
      });
    });
    

    【讨论】:

      【解决方案2】:

      事实证明,我需要的解决方案比我想象的要简单得多。我需要根据 if 语句的结果将布尔值传递给渲染函数,因此我没有调用两次res.render(),而是创建了一个新变量来存储 if 语句的结果,然后将其输入res.render()所以它只会被调用一次。

      router.post('/', function(req, res) {
        var movies = JSON.parse(fs.readFileSync('movies.json'));
        var title = req.body.title;
        var isWatched = false;
        for (let value in movies) {
            if (movies[value].title === title) {
              isWatched = true;
            }
          }
        res.render('movie', { watched: isWatched} );
      });
      

      【讨论】:

        猜你喜欢
        • 2018-12-03
        • 2017-06-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-16
        • 2016-11-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多