[英]Serve image in node.js fetched from another server
我覺得這應該足夠簡單,但我無法完成這項工作。 我有一個前端命中的 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();
}
});
}
我應該緩沖圖像嗎?
僅供參考,我正在嘗試這樣做,因為我需要在 src 路徑中檢索圖像作為身份驗證憑據,並且我不希望這些圖像暴露給用戶。 因此,如果您認為有比我正在嘗試的更好的解決方案,請隨時提出建議。 :)
謝謝!
如果有人正在尋找答案而上述方法對您不起作用,請嘗試像這樣的請求模塊。
首先包含模塊
var request = require('request')
然后:
request.get(URL, {encoding:'binary'},function(error, response){
res.writeHead(200, {'Content-Type': 'image/jpeg', 'Cache-Control': 'no-cache' });
res.end(response.body, 'binary');
});
這將繞過 URL 中的圖像並將其打印到響應中。
這應該可以正常工作,但是您遺漏了一個重要部分,即將數據寫回響應 :)
您只需要添加:
response.write(body);
response.end();
寫完標題后。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.