node.js - nodejs - 第一个参数必须是字符串或缓冲区 - 将 response.write 与 http.request 一起使用时

标签 node.js http callback

我只是想创建一个输出给定 URL 的 HTTP 状态的 Node 服务器。

当我尝试使用 res.write 刷新响应时,我收到错误: throw new TypeError('first argument must be a string or Buffer');

但是如果我用 console.log 替换它们,一切都很好(但我需要将它们写入浏览器而不是控制台)。

代码是

var server = http.createServer(function (req, res) {
    res.writeHead(200, {"Content-Type": "text/plain"});

    request({
        uri: 'http://www.google.com',
        method: 'GET',
        maxRedirects:3
    }, function(error, response, body) {
        if (!error) {
            res.write(response.statusCode);
        } else {
            //response.end(error);
            res.write(error);
        }
    });     

    res.end();
});
server.listen(9999);

我相信我应该在某处添加回调,但很困惑,感谢任何帮助。

最佳答案

我收到此错误消息,其中提到 options.body

我原来有这个

request.post({
    url: apiServerBaseUrl + '/v1/verify',
    body: {
        email: req.user.email
    }
});

我改成这样了:

request.post({
    url: apiServerBaseUrl + '/v1/verify',
    body: JSON.stringify({
        email: req.user.email
    })
});

它现在似乎可以在没有错误消息的情况下工作......不过似乎是错误。我认为这是更正式的方式:

 request.post({
        url: apiServerBaseUrl + '/v1/verify',
        json: true,
        body: {
            email: req.user.email
        }
    });

关于node.js - nodejs - 第一个参数必须是字符串或缓冲区 - 将 response.write 与 http.request 一起使用时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14835582/

相关文章:

Javascript 类似于 Java 8 上的 "Promise.all"(可能使用 lambda)

python - 从 Flask 应用程序发起的 Bokeh 服务器回调

php - 如何传递对 call_user_func 的引用?

mysql - Sequelize 原始查询返回 TextRows 数组

node.js - 如何公开托管 OHIF 查看器

javascript - Angular JS 将 base64 数组发送到 NodeJs 服务器 - Allow-Access-Control-Origin

http - 如何重新组装tcp段?

node.js - Sentry 不会向所需邮件抛出错误

javascript - Express - 在单个请求中向浏览器发送页面和自定义数据?

http - HTTP 中的内容编码与传输编码