我正在尝试在 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/