gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:54:15 26 4
gpt4 key购买 nike

我是 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com