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

标签 node.js http error-handling syntax-error

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

相关文章:

javascript - Jest + NodeJS 中的 super 测试,异步/等待

http - 浏览器的永久 HTTP 重定向

http - 使用 GET 查询参数发布到 URI?

php - 将goto替换为while循环?

node.js - git 排除文件夹中除子目录之外的所有内容

json - 如何使用 Node.js 将 JSON 数组转换为 CSV?

java - 如何通过发送 POST 查询通过 URL 打开新页面?

tsql - 外键约束冲突,但行仍然插入?

vb6 - 你为什么要使用 "On Error Goto 0"?

node.js - Windows IIS 与 Next js 应用程序内部服务器错误 500