在 node.js 中提供从另一台服务器获取的图像

Tre*_*els 3 javascript rendering image node.js

我觉得这应该足够简单,但我无法完成这项工作。我有一个前端命中的 URL。这会触发节点从另一台服务器获取图像。接下来我希望节点将图像作为响应发送。这部分对我不起作用。

render: function(img,response){
    request.get(URL, function (error, res, body) {
        if (!error && res.statusCode == 200) {
            response.setHeader('Content-Type', 'image/png');
            response.writeHead(200);
            response.write(body);
            response.end();
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

我应该缓冲图像吗?

仅供参考,我正在尝试这样做,因为我需要在 src 路径中检索图像作为身份验证凭据,并且我不希望这些图像暴露给用户。因此,如果您认为有比我正在尝试的更好的解决方案,请随时提出建议。:)

谢谢!

小智 5

如果有人正在寻找答案而上述方法对您不起作用,请尝试像这样的请求模块。

首先包含模块

var request = require('request')
Run Code Online (Sandbox Code Playgroud)

然后:

request.get(URL, {encoding:'binary'},function(error, response){
             res.writeHead(200, {'Content-Type': 'image/jpeg', 'Cache-Control': 'no-cache' });
             res.end(response.body, 'binary');
        });
Run Code Online (Sandbox Code Playgroud)

这将绕过 URL 中的图像并将其打印到响应中。