在node.js中发送HTTP响应

我正在尝试在节点中发送一个http响应,以在浏览器中打印结果。 简化的源代码如下。 基本上,所有的variables都是在程序的某个地方定义的,所以这不应该成为问题。 当我尝试运行脚本时,我不断收到错误:

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/'); } }); 

此错误通常是由于尝试使用错误的参数types调用response.write而导致的。 看看它build议的文档:

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

这个方法发信号给服务器所有的响应标题和主体已经被发送; 该服务器应该考虑完成此消息。 response.end()方法必须在每个响应中调用。

如果指定了数据 ,则相当于调用response.write(data,encoding),后跟response.end()。

现在response.write( chunk, encoding )期望chunk是一个string,所以当你调用res.end({files: fileInfos})时,它似乎不可能把这个对象的内容写成一个string。

您可以使用JSON.stringify()在将JavaScript对象发送到客户端之前将其转换为string。

 res.end(JSON.stringify({files: fileInfos}));