在Node.js中重定向之后

时间:2013-01-24 03:13:10

标签: javascript node.js redirect proxy http-headers

我正在使用代理从Google文档下载文件。由于Google Drive API为非gdrive文件类型(pdf,txt,jpeg)提供的下载网址是重定向并且已阅读[1][2],因此我决定使用follow-redirects library。因此当你点击http://localhost:3000/oauth2_download?accessToken=x&url=my_url,其中x是我的GDrive access_token,url是,例如,https://docs.google.com/uc?id=0B_31K_MP92hUNjljYjIyMzgtZTBmNS00MGMwLWIxNmQtYjMyNDFiYjY0MTJl&export=download,该文件应该被下载。但是,浏览器会将我发送到Google文档登录页面(如果您登录Google文档,则在浏览器中点击https://docs.google.com/uc?id=0B_31K_MP92hUNjljYjIyMzgtZTBmNS00MGMwLWIxNmQtYjMyNDFiYjY0MTJl&export=download下载文件)表示标题未正确发送。任何想法我应该如何使用'follow-redirects'库来处理这个问题?提前谢谢!

//var https = require('https');
var https = require('follow-redirects').https;
var app = require('express')();
var urllib = require('url');
// Downloads the file using OAuth2. Tested on Google Drive
app.get('/oauth2_download', function(req, res){
    var url = req.param('url');
    var accessToken = req.param('accessToken');
    var headers = { "Authorization": "Bearer " + accessToken }
    var searchname = urllib.parse(url).search;
    var hostname = urllib.parse(url).hostname;
    var pathname = urllib.parse(url).pathname;
    if (url && accessToken) {
        // downloading file with streaming
        var options = {
            hostname: hostname,
            port: 443,
            path: pathname + searchname,
            method: 'GET',
            headers: headers
        };
        https.request(options, function(response){
            for (var key in response.headers) {
                res.setHeader(key, response.headers[key]);
            }
            response.on('data', function(chunk) {
                res.write(chunk);
            });
            response.on('end', function() {
                res.end();
            });
            //console.log("Done downloading using OAuth2");
        }).on('error', function(e) {
            console.error(e);
        }).end();
    } else {
        res.send(404);
        res.end();
    }
});

0 个答案:

没有答案