简体   繁体   English

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

[英]nodejs - first argument must be a string or Buffer - when using response.write with http.request

I'm simply trying to create a node server that outputs the HTTP status of a given URL.我只是想创建一个输出给定 URL 的 HTTP 状态的节点服务器。

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');当我尝试使用 res.write 刷新响应时,出现错误: 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).但是如果我用 console.log 替换它们,一切都很好(但我需要将它们写入浏览器而不是控制台)。

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.我相信我应该在某处添加一个回调,但很困惑,任何帮助表示赞赏。

I get this error message and it mentions options.body我收到此错误消息,其中提到options.body

I had this originally我原来有这个

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

I changed it to this:我把它改成这样:

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

and it seems to work now without the error message...seems like bug though.它现在似乎可以在没有错误消息的情况下工作......虽然看起来像错误。 I think this is the more official way to do it:我认为这是更正式的方式:

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

response.statusCode is a number, eg response.statusCode === 200 , not '200' . response.statusCode是一个数字,例如response.statusCode === 200 ,而不是'200' As the error message says, write expects a string or Buffer object, so you must convert it.正如错误消息所说, write需要一个stringBuffer对象,因此您必须对其进行转换。

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.应该在回调内部,就在您的write调用下方。

Request takes a callback method, its async!请求采用回调方法,它是异步的! So I am assuming, by the time the callback is executed the res.end() might get called.所以我假设,在执行回调时res.end()可能会被调用。 Try closing the request within the callback.尝试在回调中关闭请求。

Well, obviously you are trying to send something which is not a string or buffer.好吧,显然您正在尝试发送不是字符串或缓冲区的内容。 :) It works with console, because console accepts anything. :) 它适用于控制台,因为控制台接受任何东西。 Simple example:简单的例子:

var obj = { test : "test" };
console.log( obj ); // works
res.write( obj ); // fails

One way to convert anything to string is to do that:将任何内容转换为字符串的一种方法是这样做:

res.write( "" + obj );

whenever you are trying to send something.每当您尝试发送某些东西时。 The other way is to call .toString() method:另一种方法是调用.toString()方法:

res.write( obj.toString( ) );

Note that it still might not be what you are looking for.请注意,它可能仍然不是您想要的。 You should always pass strings/buffers to .write without such tricks.您应该始终将字符串/缓冲区传递给.write而不使用这些技巧。

As a side note: I assume that request is a asynchronous operation.作为旁注:我假设request是异步操作。 If that's the case, then res.end();如果是这样,那么res.end(); will be called before any writing, ie any writing will fail anyway ( because the connection will be closed at that point ).将在任何写入之前被调用,即任何写入都会失败(因为连接将在那时关闭)。 Move that line into the handler:将该行移到处理程序中:

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

if u want to write a JSON object to the response then change the header content type to application/json如果您想将 JSON 对象写入响应,则将标头内容类型更改为 application/json

response.writeHead(200, {"Content-Type": "application/json"});
var d = new Date(parseURL.query.iso);
var postData = {
    "hour" : d.getHours(),
    "minute" : d.getMinutes(),
    "second" : d.getSeconds()
}
response.write(postData)
response.end();

使用 ajax(XMLhttpRequest) 时还有另一种可能性(在这种情况下不是),在将信息发送回客户端时,您应该使用res.send(responsetext)而不是 res.end(responsetext)

Although the question is solved, sharing knowledge for clarification of the correct meaning of the error.虽然问题解决了,分享知识以澄清错误的正确含义。

The error says that the parameter needed to the concerned breaking function is not in the required format ie string or Buffer该错误表示相关中断函数所需的参数不是所需的格式,即字符串或缓冲区

The solution is to change the parameter to string解决方法是将参数改为字符串

breakingFunction(JSON.stringify(offendingParameter), ... other params...);

or buffer或缓冲

breakingFunction(BSON.serialize(offendingParameter), ... other params...);

The first argument must be one of type string or Buffer.第一个参数必须是字符串或缓冲区类型之一。 Received type object接收到的类型对象

 at write_

I was getting like the above error while I passing body data to the request module.当我将正文数据传递给请求模块时,我遇到了上述错误。

I have passed another parameter that is JSON: true and its working.我已经传递了另一个参数是 JSON: true 和它的工作。

var option={
url:"https://myfirstwebsite/v1/appdata",
json:true,
body:{name:'xyz',age:30},
headers://my credential
}
rp(option)
.then((res)=>{
res.send({response:res});})
.catch((error)=>{
res.send({response:error});})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM