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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14835582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 17:09:03  来源:igfitidea点击:

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

node.jshttpcallback

提问by umutm

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.

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

采纳答案by Gaurav Agarwal

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.

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

回答by loganfsmyth

response.statusCodeis a number, e.g. response.statusCode === 200, not '200'. As the error message says, writeexpects a stringor Bufferobject, so you must convert it.

response.statusCode是一个数字,例如response.statusCode === 200,不是'200'。正如错误消息所说,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 writecalls.

不过,您对回调评论的看法也是正确的。res.end();应该在回调里面,就在你的write电话下面。

回答by Alexander Mills

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

回答by freakish

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 .writewithout such tricks.

请注意,它可能仍然不是您要查找的内容。您应该始终将字符串/缓冲区传递给.write没有此类技巧。

As a side note: I assume that requestis a asynchronous operation. If that's the case, then res.end();will be called before any writing, i.e. any writing will fail anyway ( because the connection will be closed at that point ). Move that line into the handler:

作为旁注:我假设这request是一个异步操作。如果是这种情况,则将res.end();在任何写入之前调用,即无论如何任何写入都会失败(因为连接将在该点关闭)。将该行移动到处理程序中:

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

回答by Mohsin Muzawar

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

回答by Prajith P

And there is another possibility (not in this case) when working with ajax(XMLhttpRequest), while sending information back to the client end you should use res.send(responsetext)instead of res.end(responsetext)

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

回答by xameeramir

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 i.e. 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...);

回答by A. PRABIN SARAB

The first argument must be one of type string or Buffer. Received type object

第一个参数必须是 string 或 Buffer 类型之一。接收类型对象

 at write_
 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});})