nodejs - 第一个参数必须是字符串或缓冲区 - 当使用 response.write 和 http.request 时 [英] nodejs - first argument must be a string or Buffer - when using response.write with http.request

查看:14
本文介绍了nodejs - 第一个参数必须是字符串或缓冲区 - 当使用 response.write 和 http.request 时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想创建一个节点服务器来输出给定 URL 的 HTTP 状态.

I'm simply trying to create a node server that outputs the HTTP status of a given URL.

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

When I try to flush the response with res.write, I get the error: throw new TypeError('first argument must be a string or Buffer');

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

But if I replace them with console.log, everything is fine (but I need to write them to the browser not the console).

代码是

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);

我相信我应该在某处添加回调,但很困惑,任何帮助表示赞赏.

I believe I should add a callback somewhere but pretty confused and any help is appreciated.

推荐答案

Request 采用回调方法,它是异步的!所以我假设,当回调被执行时 res.end() 可能会被调用.尝试在回调中关闭请求.

Request takes a callback method, its async! So I am assuming, by the time the callback is executed the res.end() might get called. Try closing the request within the callback.

这篇关于nodejs - 第一个参数必须是字符串或缓冲区 - 当使用 response.write 和 http.request 时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆