最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Serve image in node.js fetched from another server - Stack Overflow

programmeradmin1浏览0评论

I feel like this should be simple enough, but I am having trouble making this work. I have a URL that the front-end hits. This triggers node to fetch an image from another server. Next I want node to send the image as the response. This part is not working for me.

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

Should I be buffering the image instead?

FYI I am trying to do this this way because the image i need to retrieve as authentication credentials in the src path, and I don't want those exposed to the user. So if you think that there is a better solution than what I am trying, please feel free to suggest. :)

Thanks!

I feel like this should be simple enough, but I am having trouble making this work. I have a URL that the front-end hits. This triggers node to fetch an image from another server. Next I want node to send the image as the response. This part is not working for me.

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

Should I be buffering the image instead?

FYI I am trying to do this this way because the image i need to retrieve as authentication credentials in the src path, and I don't want those exposed to the user. So if you think that there is a better solution than what I am trying, please feel free to suggest. :)

Thanks!

Share Improve this question edited Oct 30, 2014 at 17:11 Trey Eckels asked Oct 30, 2014 at 16:31 Trey EckelsTrey Eckels 3483 silver badges10 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

If someone is looking for an answer and the above did not work for you, try the request module like this.

First include the module

var request = require('request')

then:

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

This will bypass the image from the URL and print it into the response.

That should work fine, but you've left out one important part, writing the data back to the response :)

You just need to add:

response.write(body); 
response.end(); 

After writing the headers.

发布评论

评论列表(0)

  1. 暂无评论