How to request images and output image in Node.js

跟風遠走 提交于 2020-07-08 20:52:44

问题


I try to get the image and display on a url. and I use request module.

For example, I want to get the image https://www.google.com/images/srpr/logo11w.png, and display on my url http://example.com/google/logo.

Or display by <img src="http://example.com/google/logo" />.

And I try to use 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();
  })
})

but the response is not a image. How to get image and output?

Please give me some suggestion about the question. THANKS.


回答1:


Try specifying encoding: null when making the request so that the response body is a Buffer that you can directly write to the response stream:

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

On the other hand if you do not specify encoding: null, the body parameter will be a String instead of a Buffer.




回答2:


That seems an overkill, you can just ask the browser the get the url directly like this;

app.get("/google/logo", function(req, res) {
res.writeHead(302, {location:"https://www.google.com/images/srpr/logo11w.png"});
res.end();
})


来源:https://stackoverflow.com/questions/28779503/how-to-request-images-and-output-image-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!