我正在尝试根据输入网址创建图像代理。我当前的代码让它复制确切的一些标题并将它们返回给客户端,但我尝试了各种方法,并且响应要么继续尝试永远加载,要么说“图像因为包含错误而无法显示”。这是我的代理人:
var http = require('http'),
url = require('url');
exports.show = function (req, res, next) {
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
var options = {
host: "api.com",
path: "/dgtf/20080303201247771409000000.jpg"
};
var callback = function(response) {
var completeResponse = '';
response.on('data', function (chunk) {
completeResponse += chunk;
});
response.on('end', function() {
res.writeHead(200, {'Content-Type': response.headers['content-type'], 'Content-Length': response.headers['content-length'] });
res.end(completeResponse, 'binary');
});
};
http.request(options, callback).end();
};
答案 0 :(得分:4)
避免将二进制数据转换为字符串,除非您知道自己在做什么。你可能会尝试类似的东西:
var http = require('http'),
url = require('url');
exports.show = function (req, res, next) {
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
var options = {
host: "api.com",
path: "/dgtf/20080303201247771409000000.jpg"
};
var callback = function(response) {
if (response.statusCode === 200) {
res.writeHead(200, {
'Content-Type': response.headers['content-type']
});
response.pipe(res);
} else {
res.writeHead(response.statusCode);
res.end();
}
};
http.request(options, callback).end();
};