gpt4 book ai didi

javascript - Google 云端硬盘 - 列出文件 - Javascript

转载 作者:行者123 更新时间:2023-11-28 01:25:09 25 4
gpt4 key购买 nike

我正在尝试在 Google 云端硬盘上列出我的文件。

我几周来一直试图完成这项工作,但没有成功。我一直在尝试 PHP,现在我已经转向 Javascript,看看是否可以找到任何可以工作的示例。

这是我正在研究的示例

http://runnable.com/UTlPMF-f2W1TAAAj/list-files-on-google-drive

所以我已经上传了我的文件,在我的 Google 控制台上启用了 Drive API,拥有正确的范围,拥有客户端 key 和客户端 ID

我正在使用自己的帐户在本地主机上进行测试。

到目前为止,主 html 页面已加载,我单击登录按钮,然后出现一个空白弹出窗口,没有其他内容,没有错误。

这是我的文件

oauth.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);

index.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>

package.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 环境变量,该变量可能是动态的,或者与您在 api 控制台上注册的不同。

其次,您没有保存第一次在同意屏幕上允许访问时获得的refresh_token,可能是access_token已过期,因此您已使用该refresh_token刷新它

但是,我建议使用 google-api-nodejs-client用于访问 google api,其官方 google api 客户端库。

如果您使用此库,则无需担心刷新过期的访问 token ,并且可以通过库 API 和缓存获得干净的语法。

我在博客上介绍了它 http://manan-vaghasiya.in/post/integrating-your-node.js-app-with-google-apis

关于javascript - Google 云端硬盘 - 列出文件 - Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22775081/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com