node.js - NodeJs错误: Can't set headers after they are sent

标签 node.js express

我是 Nodejs 新手,并且遇到了这个错误:发送后无法设置 header 。下面是我的代码。请帮忙。我使用 postman 来测试这段代码。前 2 次点击正常,但在第 3 次点击时出现此错误。

const http = require('http');

const fs = require('fs')

module.exports.verifyPyeval5 = function(request, response){
    let filePath = "D:/PyEval/NewPyEvalRequests/solution.txt";  
    fs.readFile(filePath, 'utf8', function (err,data) {
       var json = JSON.parse(data);
        post_call(json,function(res){
            response.status(200)
        .json(res);
        });
    });   

};

var post_call = function(new_val,callback){
    var post_req = http.request(post_options, function(res) { 
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
            callback(chunk);
        });
      });
      post_req.write(JSON.stringify(new_val));
      post_req.end();

};

var post_options = {
      host: 'acclabserv',
      port: '8080',
      path: '/generate',
      method: 'POST',
      headers: {
          'Content-Type': 'application/json'
      }
  };

最佳答案

我知道问题出在回调函数上,它被多次调用。

var post_call = function(new_val,callback){
    var post_req = http.request(post_options, function(res) { 
        res.setEncoding('utf8');
        var str = null;
        res.on('data', function (chunk) {
            str += chunk;
        });
      res.on('end', function () {
            callback(str);
        });
      });
      post_req.write(JSON.stringify(new_val));
      post_req.end();

};

这里还有一件事要注意,我不知道卡盘的类型,如果它是一个对象,并且您想要对象数组作为响应,那么您可以使用它

var str = []; //in req.on('data') str.push(chunck)

关于node.js - NodeJs错误: Can't set headers after they are sent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45145478/

相关文章:

javascript - 使用node.js从文件中读取环境变量

javascript - 设置空数组索引

javascript - 如何将发布请求重定向到 node.js 中的其他 url?

node.js - 如何使用redis在 Node 中缓存查询数据

javascript - 通过Apache Pig UDF读取javascript文件

javascript - 在 Mongoose 外部的函数中返回数据

node.js - 无法让 Node Express 服务器运行

node.js - expressjs 日志记录的最佳实践是什么?

javascript - 向变量添加值不起作用,仅附加

javascript - 如何在javascript中计算数组内的数组元素?