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
How to request images and output image in Node.js
提问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:
我尝试使用request和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.
请给我一些关于这个问题的建议。谢谢。
回答by Darin Dimitrov
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:
尝试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 body
parameter 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();
})