node中如何读取远程的图片并显示出来?

用的是express框架,读取https://pin.aliyun.com/get_img?sessionid=1这个图片的内容,用http://localhost/identify 把图片显示出来,代码如下,运行后图片显示框框,没显示出图片:


router.get('/identify',function(req,res,next){
    var opts={
        url:'https://pin.aliyun.com/get_img?sessionid=1'
    }
    request.get(opts, function (err, response, body) {
        var type = response.headers["content-type"];
        res.writeHead(200,{"Content-Type":type});
        res.write(body);
        res.end();
    })
})
阅读 6.6k
2 个回答

多加点日志打印调试一下

这个问题是使用request导致的,看request的源码中readResponseBody处理的部分,有一段这个

  if (self.encoding !== null) {
      console.log('response.body.toString ');
    response.body = response.body.toString(self.encoding)
  }

如果self.encoding是undefined时候,也进入了这段逻辑,导致编码错误了

因此调用的时候,必须强制指定encoding为null,文档中也有说明

encoding - encoding to be used on setEncoding of response data. If null, the body is returned as a Buffer. Anything else (including the default value of undefined) will be passed as the encoding parameter to toString() (meaning this is effectively utf8 by default). (Note: if you expect binary data, you should set encoding: null.)

改成这样就行了

router.get('/identify',function(req,res,next){

var opts={
    url:'https://pin.aliyun.com/get_img?sessionid=1',
    encoding:null
}
request.get(opts, function (err, response, body) {
    var type = response.headers["content-type"];
    res.writeHead(200,{"Content-Type":type});
    res.write(body);
    res.end();
})

})

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题