node.js报TypeError: argument should be a Buffer解决

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/u014204541/article/details/84324937

这个错误是由于传入的参数不是字符串或者buffer造成的,我的代码如下

var http = require('http')
var request = require('request')

// 1. 创建 Server
var server = http.createServer()

server.on('request', function (req, res) {
	 res.writeHead(200,{'Content-Type':'application/json;charset=utf-8'});//设置response编码为utf-8
  var url = req.url
   console.log("url:"+url);
   //发送请求豆瓣获取json数据
    request({
        url: "https://api.douban.com/"+url,
        method: "POST",
        json: true,
        headers: {
            "content-type": "application/xml",
        },
        body: ""
    }, function(error, response, body) {
        if (!error && response.statusCode == 200) {
            console.log(body) // 请求成功的处理逻辑
			//res.write(JSON.stringify(body))
			res.write(body)
			res.end()
        }
    });

})

// 3. 绑定端口号,启动服务
server.listen(3000, function () {
  console.log('running...')
})

其中我请求的豆瓣返回的是json,而我直接使用res.write(body),因为body是json对象报错了,
在这里插入图片描述
把res.write(body)改成res.write(JSON.stringify(body))即可解决这个错误,
如果你的对象不是json对象,其实可以直接body.toString()就可以了

猜你喜欢

转载自blog.csdn.net/u014204541/article/details/84324937