微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 尝试在node-js / express中代理图像

当我尝试通过Express访问时,我得到一个损坏的图像链接

app.get('/fileThumbnail', function(req, res) {

var url = proxiedURL +"?" + querystring.stringify(req.query);

logger.info('/fileThumbnail going to url', url);

request.get(url, function(err, response, img) {
    logger.info("response:", response.statusCode, response.headers['content-type']);
    if (!err && response.statusCode === 200) {
        res.writeHead(200, {
            'Content-Type': response.headers['content-type']
        });
        // response.pipe(res);  // not working
        res.writeHead(200, response.headers);
        res.end(img, 'binary');
    } else res.send("Error occurred:", err, "; status code: ", response.statusCode);
})
});

缩略图来自PHP服务器:

if (!$thumbnail) {
    $thumbnail = $_SERVER['DOCUMENT_ROOT'].'/images/spacer.gif';
}


// Write the thumbnail
header('Content-Type: '.image_type_to_mime_type(exif_imagetype($thumbnail)));
header('Content-length: '.filesize($thumbnail));
print file_get_contents($thumbnail,FILE_BINARY);

尝试过几件事;响应头如下:

Access-Control-Allow-Methods:GET,POST,PUT,DELETE,OPTIONS
access-control-allow-origin:*
cache-control:no-store, no-cache, must-revalidate, post-check=0, pre-check=0
connection:Keep-Alive
content-length:894
content-type:image/jpeg
date:Mon, 17 Nov 2014 22:13:24 GMT
expires:Thu, 19 Nov 1981 08:52:00 GMT
keep-alive:timeout=5, max=100
pragma:no-cache
server:Apache/2.2.15
X-Powered-By:Express

解决方法:

像往常一样,简单的解决方案是最好的.只需npm安装请求然后像这样使用它:

var request = require('request');

app.get('/fileThumbnail', function(req, res) {
    var url = proxiedURL +"?" + querystring.stringify(req.query);
    logger.info('/fileThumbnail going to url', url); 
    request.get(url).pipe(res);
});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐