nodejs - 第一个参数必须是字符串或Buffer - 当使用response.write与http.request时 [英] nodejs - first argument must be a string or Buffer - when using response.write with http.request
问题描述
我尝试创建一个节点服务器,输出给定URL的HTTP状态。当我尝试使用res.write清除响应时,我得到的错误:throw new TypeError('第一个参数必须是字符串或缓冲区');
但是如果我把它们替换为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);
我相信我应该在某处添加一个回调,但很困惑,任何帮助。
response.statusCode
是一个数字,例如 response.statusCode === 200
,而不是'200'
。如错误消息所示,写需要
字符串
或缓冲区
对象,因此必须转换它。
res.write(response.statusCode.toString());
你对回调评论也是正确的。 res.end();
应该在回调内,就在写
下。
I'm simply trying to create a node server that outputs the HTTP status of a given URL.
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');
But if I replace them with console.log, everything is fine (but I need to write them to the browser not the console).
The code is
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.
response.statusCode
is a number, e.g. response.statusCode === 200
, not '200'
. As the error message says, write
expects a string
or Buffer
object, so you must convert it.
res.write(response.statusCode.toString());
You are also correct about your callback comment though. res.end();
should be inside the callback, just below your write
calls.
这篇关于nodejs - 第一个参数必须是字符串或Buffer - 当使用response.write与http.request时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!