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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28779503/
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-10-28 09:32:59  来源:igfitidea点击:

How to request images and output image in Node.js

javascriptnode.jsexpressrequest

提问by kenticny

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

我尝试获取图像并显示在 url 上。我使用请求模块。

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.

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

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

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

And I try to use requestand express:

我尝试使用requestexpress

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.

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

回答by Darin Dimitrov

Try specifying encoding: nullwhen making the request so that the response body is a Bufferthat you can directly write to the response stream:

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

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

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

回答by Safi

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

这似乎有点矫枉过正,你可以像这样直接让浏览器获取 url;

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