我正在研究从 Google Docs 下载文件的代理。由于 Google Drive API 为非 gdrive 文件类型(pdf、txt、jpeg)提供的下载 url 是重定向并且已阅读[1]和[2],因此我决定使用follow-redirects library。因此,当您点击http://localhost:3000/oauth2_download?accessToken=x&url=my_url
where x is my GDrive access_token, url 时,https://docs.google.com/uc?id=0B_31K_MP92hUNjljYjIyMzgtZTBmNS00MGMwLWIxNmQtYjMyNDFiYjY0MTJl&export=download
应该下载该文件。但是,浏览器将我发送到 Google Docs 登录页面(https://docs.google.com/uc?id=0B_31K_MP92hUNjljYjIyMzgtZTBmNS00MGMwLWIxNmQtYjMyNDFiYjY0MTJl&export=download
如果您已登录 Google Docs,则在浏览器中点击会下载文件)意味着未正确发送标头。知道我应该如何使用“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();
}
});