我正在使用 node.js 0.10.33 并请求 2.51.0。
在下面的示例中,我构建了一个使用请求代理图像的简单 Web 服务器。设置了两条路由来代理同一个图像..
/pipe只是将原始请求通过管道传输到响应
/callback等待请求回调并将响应标头和正文发送到响应。
管道示例按预期工作,但回调路由不会呈现图像。标题和正文似乎相同。
回调路由导致图像中断怎么办?
这是示例代码:
var http = require('http');
var request = require('request');
var imgUrl = 'https://developer.salesforce.com/forums/profilephoto/729F00000005O41/T';
var server = http.createServer(function(req, res) {
if(req.url === '/pipe') {
// normal pipe works
request.get(imgUrl).pipe(res);
} else if(req.url === '/callback') {
// callback example doesn't
request.get(imgUrl, function(err, resp, body) {
if(err) {
throw(err);
} else {
res.writeHead(200, resp.headers);
res.end(body);
}
});
} else {
res.writeHead(200, {
'Content-Type': 'text/html'
});
res.write('<html><head></head><body>');
// test the piped image
res.write('<div><h2>Piped</h2><img src="/pipe" /></div>');
// test the image from the callback
res.write('<div><h2>Callback</h2><img src="/callback" /></div>');
res.write('</body></html>');
res.end();
}
});
server.listen(3000);
结果在这