如何在Node.js中请求图像并输出图像

2024-01-03

我尝试获取图像并显示在网址上。我用request https://github.com/request/request module.

例如我想获取图像https://www.google.com/images/srpr/logo11w.png,并显示在我的网址上http://example.com/google/logo.

或显示方式<img src="http://example.com/google/logo" />.

我尝试使用request and express:

app.get("/google/logo", function(req, res) {
  request.get("https://www.google.com/images/srpr/logo11w.png", 
        function(err, result, body) {
    res.writeHead(200, {"Content-Type": "image/png"});
    res.write(body);
    res.end();
  })
})

但响应不是图像。如何获取图像并输出?

请给我一些关于这个问题的建议。谢谢。


尝试指定encoding: null发出请求时,响应正文是Buffer您可以直接写入响应流:

app.get("/google/logo", function(req, res) {
    var requestSettings = {
        url: 'https://www.google.com/images/srpr/logo11w.png',
        method: 'GET',
        encoding: null
    };

    request(requestSettings, function(error, response, body) {
        res.set('Content-Type', 'image/png');
        res.send(body);
    });
});

另一方面,如果您不指定encoding: null, the body参数将是字符串而不是缓冲区。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在Node.js中请求图像并输出图像 的相关文章

随机推荐