在我的应用程序代码中,对于一组特定的 API,我正在发出如下所示的 NodeJS 请求,它应该返回一个图像作为正文。同样的请求在 Postman 上运行良好(我可以看到图像)。
module.exports = {
getThumbnail: function (thumbnailUrn, env, token, onsuccess){
request({
url: config.baseURL(env) + config.thumbail(thumbnailUrn),
method: "GET",
headers: {
'Authorization': 'Bearer ' + token,
}
}, function (error, response, body) {
// error check removed for simplicity...
onsuccess(body);
});
}
}
以上代码在我自己的安全检查下运行并添加了 token header 。它工作正常(请求调用返回 200/OK)。
现在,在我的应用程序路由器上,我想将其作为图像进行响应,但输出未被解释为图像。这是我所拥有的:
var dm = require(/*the above code*/);
// express router
var express = require('express');
var router = express.Router();
router.get('/getThumbnail', function (req, res) {
var urn = req.query.urn;
dm.getThumbnail(urn, req.session.env, req.session.oauthcode, function (thumb) {
res.writeHead(200,
{
'Content-Type': 'image/png'
}
);
// at this point, the 'thumb' variable is filled
// but I believe is not properly encoded...
// or maybe the res.end output is missing something...
res.end(thumb, 'binary');
});
});
module.exports = router;
编辑:正如Nodari Lipartiya评论的那样,这是一种代理行为(服务器(用图像响应)-> 代理(node.js/重新发送到客户端)-> 最终用户)
最佳答案
我不确定 thumb
返回了什么,但以下代码片段似乎对我有用(为简单起见绕过了 Express):
var http = require("http")
var fs = require("fs")
var server = http.createServer(listener)
server.listen(() => {
console.log(server.address().port)
})
var binary = fs.readFileSync("path to local image")
function listener(req, resp) {
resp.writeHead(200,
{
'Content-Type': 'image/png'
}
);
resp.end(new Buffer(binary), "binary")
}
如果将其包装在 Buffer
中会怎样?
关于javascript - 在 NodeJS 上重定向图像请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37349298/