谷歌驱动器 - 列表文件 - Javascript
Google Drive - List Files - Javascript
我正在尝试在Google云端硬盘上列出我的文件。
几个星期以来,我一直在尝试完成这项工作,但没有成功。我一直在尝试PHP,现在我已经进入Javascript,看看我是否可以得到任何示例。
这是我正在处理的示例
http://runnable.com/UTlPMF-f2W1TAAAj/list-files-on-google-drive
因此,我已经上传了文件,在我的 Google 控制台上启用了云端硬盘 API,具有正确的范围,具有客户端密钥、客户端 ID
我正在使用自己的帐户在本地主机上进行测试。
到目前为止,主html页面加载,我单击登录按钮,然后有一个空白弹出窗口,没有别的,没有错误。
这是我的文件
欧斯.js
var request = require('request')
, qs = require('qs')
, callbackURL = 'http://'+process.env.OPENSHIFT_APP_DNS+'/callback';
var state = ''
, access_token = ''
, token_type = ''
, expires = '';
function login(req, res) {
state = Math.floor(Math.random() * 1e19);
exports.state = state;
var params = {
response_type: 'code',
client_id: 'myclientid',
redirect_uri: callbackURL,
state: state,
display: 'popup',
scope: 'https://www.googleapis.com/auth/drive' // specify the "Google Drive" scope
};
params = qs.stringify(params);
res.writeHead(200, {'Content-type': 'text/plain'});
res.end('https://accounts.google.com/o/oauth2/auth?'+params);
}
function callback(req, res) {
var code = req.query.code
, cb_state = req.query.state
, error = req.query.error;
if (state == cb_state) {
if (code !== undefined) {
var params = {
code: code,
client_id: 'myclientid',
client_secret: 'myclientsecret',
redirect_uri: callbackURL,
grant_type: 'authorization_code'
};
request.post('https://accounts.google.com/o/oauth2/token', {form:params}, function(err, resp, body) {
var results = JSON.parse(body);
exports.access_token = access_token = results.access_token;
exports.token_type = token_type = results.token_type;
exports.expires = expires = results.expires_in;
console.log("Connected to Google");
// close the popup
var output = '<html><head></head><body onload="window.close();">Close this window</body></html>';
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(output);
});
} else {
console.error('Code is undefined: '+code);
console.error('Error: '+ error);
}
} else {
console.log('Mismatch with variable "state". Redirecting to /');
res.redirect('/');
}
}
exports.login = login;
exports.callback = callback;
服务器.js
var express = require('express')
, request = require('request')
, oauth = require('./oauth')
, app = express();
// Setup middleware
app.use(express.static(__dirname));
// List out file that are in your Google Drive
app.get('/list', function(req, res) {
// Check to see if user has an access_token first
if (oauth.access_token) {
// URL endpoint and params needed to make the API call
var url = 'https://www.googleapis.com/drive/v2/files';
var params = {
access_token: oauth.access_token
};
// Send the API request
request.get({url:url, qs:params}, function(err, resp, body) {
// Handle any errors that may occur
if (err) return console.error("Error occured: ", err);
var list = JSON.parse(body);
if (list.error) return console.error("Error returned from Google: ", list.error);
// Generate output
if (list.items && list.items.length > 0) {
var file = ''
, iconLink = ''
, link = ''
, output = '<h1>Your Google Drive</h1><ul>';
for(var i=0; i<list.items.length; i++) {
file = list.items[i].title;
iconLink = list.items[i].iconLink;
link = list.items[i].alternateLink;
output += '<li style="list-style- image:url('+iconLink+');"><a href="'+link+'" target="_blank">'+file+'</a></li>';
}
output += '</ul>';
//Send output as response
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(output);
} else { // Alternate output if no files exist on Drive
console.log('Could not retrieve any items.');
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('<p>Your drive appears to be empty.</p>')
}
});
// If no access_token was found, start the OAuth flow
} else {
console.log("Could not determine if user was authed. Redirecting to /");
res.redirect('/');
}
});
// Handle OAuth Routes
app.get('/login', oauth.login);
app.get('/callback', oauth.callback);
app.listen(80);
索引.html
<html>
<head>
<title>Google server-side OAuth v2 Example</title>
<script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
var url = '';
var b = '';
$(document).ready(function() {
$.get('/login', function(data) {
url = data;
});
var interval = window.setInterval((function() {
if (b.closed) {
window.clearInterval(interval);
window.location = './list';
}
}),1000);
});
</script>
<link rel="stylesheet" href="styles.css" type="text/css">
</head>
<body>
<h1 id="header">Google Drive: Retrieve list of files</h1>
<p>Get started by logging into your Google account using the button below</p>
<button id="login" onclick="b = window.open(url, 'window', 'status=0,menubar=0,resizable=1,width=500,height=800;')">Login to Google</button>
</body>
</html>
包.json
{
"name": "facebook-oauthv2-js-sdk-example",
"version": "0.0.1",
"description": "A sample code project using Google to perform server-side OAuth v2",
"dependencies": {
"express": "*",
"qs": "*",
"request": "*"
},
"engine": "node 0.6.x"
}
风格.css
body{
margin: 0;
padding: 10px;
font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
}
h1{
padding: 10px 0;
font-size: 18px;
font-weight: normal;
color: #444;
border-bottom: 1px solid #ccc;
margin: 0 0 20px;
text-transform:capitalize;
}
关于如何列出我的文件的任何想法?
首先,我看到您正在使用 openshift env 变量,该变量可能是动态的,也可能与您在 api 控制台上注册的变量不同。
其次,您没有保存首次在同意屏幕上允许访问时获得的refresh_token,也许access_token已过期,因此您可以使用该refresh_token刷新它
但是,我建议使用 google-api-nodejs-client 来访问 google api,这是其官方的 google apis 客户端库。
如果您使用此库,则无需担心刷新过期的访问令牌,并且可以通过库 API 和缓存获得干净的语法。
我在博客上写了关于它的文章http://manan-vaghasiya.in/post/integrating-your-node.js-app-with-google-apis
相关文章:
- 使用压缩的JavaScript文件(不是运行时压缩)
- 如何包含特定于每个视图angularjs的javascript文件
- 将数据从javascript文件导入VB.Net页面
- Chrome加载旧版本的Javascript文件
- 操作员”;新的“;根据我想在几个JavaScript文件中使用的类,在JavaScript中使用
- gulp-if-javascript文件,但不在gulp-useref的特定目录中
- 如何在visualstudio中调试web api时编辑javascript文件
- 关于引入外部javascript文件的问题&css通过https
- 有没有办法在tinymceiframe中加载一个外部javascript文件
- 什么'是在asp.net MVC中将本地化的resources.resx文件转换为javascript文件的有效
- 在一个javascript文件中为整个网站创建标签
- 如何在定义js文件后为外部javascript文件设置变量
- 显示IIS上javascript文件(SOAP请求)的XML响应
- ResolveUrl没有'我似乎不适合当链接到具有动态虚拟目录的外部javascript文件时
- 我应该将MVC视图特定的javascript文件放在哪个文件夹中
- Django'支持Javascript文件中的翻译
- MVC正在忽略我的Javascript文件
- 为什么不't我的ruby代码与javascript文件一起插入
- 在Javascript文件中获取PHP变量
- 如何在Windows中将Javascript文件编译成二进制文件