gpt4 book ai didi

node.js - 在 node.js 中发送 HTTP 响应

转载 作者:可可西里 更新时间:2023-11-01 17:10:40 24 4
gpt4 key购买 nike

我正在尝试在 Node 中发送一个 http 响应以在浏览器中打印结果。简化的源代码在下面。基本上,所有变量都在程序的某处定义,所以这应该不是问题。当我尝试运行脚本时,我不断收到错误消息:

    http.js:783
throw new TypeError('first argument must be a string or Buffer');

TypeError: first argument must be a string or Buffer

那么熟悉 node.js 或 javascript 语法的人可以让我知道问题出在哪里吗?

    upload = function(req, res) {
var fileInfos = [obj, obj]; //defined as an array of objects
var counter = 0;
counter -= 1;
if (!counter) {
res.end({files: fileInfos}); //files is defined.
}
};

async.forEach(urls, downloadFile, function (err) { //all params defined.
if(err){
console.error("err");
throw err;
}
else{
http.createServer(function(req, res){
upload(req1, res); //req1 defined as an array of objects.
}).listen(3000, "127.0.0.1");
console.log('Server running at http://127.0.0.1:3000/');
}
});

最佳答案

此错误通常是由于尝试使用错误类型的参数调用 response.write 引起的。查看它建议的文档:

response.end([data], [encoding])#

This method signals to the server that all of the response headers and body have been sent; that server should consider this message complete. The method, response.end(), MUST be called on each response.

If data is specified, it is equivalent to calling response.write(data, encoding) followed by response.end().

现在 response.write( chunk, encoding ) 期望 block 是一个字符串,所以当你调用 res.end({files: fileInfos}) 无法将该对象的内容写为字符串。

关于node.js - 在 node.js 中发送 HTTP 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18063245/

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