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

ken*_*cny 2 javascript request node.js express

我试图获取图像并显示在网址上.我使用请求模块.

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

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

我尝试使用请求表达:

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();
  })
})
Run Code Online (Sandbox Code Playgroud)

但响应不是图像.如何获得图像和输出?

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

Dar*_*rov 17

尝试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);
    });
});
Run Code Online (Sandbox Code Playgroud)

另一方面,如果未指定encoding: null,则body参数将是String而不是Buffer.