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

时间:2014-04-01 01:13:59

标签: javascript oauth oauth-2.0 google-drive-api

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

我一直试图在没有成功的情况下完成这几周。我一直在尝试PHP,现在我已经进入Javascript,看看我是否可以得到任何工作的例子。

这是我正在使用

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

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

我正在使用自己的帐户在localhost上进行测试。

到目前为止主要的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;

server.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"
}

的style.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;
}

有关如何列出我的文件的任何想法?

1 个答案:

答案 0 :(得分:1)

首先,我看到你使用的openhift env变量可能是动态的,或者与你在api控制台上注册的不一样。

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

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

如果你使用这个库,那么你不必担心刷新过期的访问令牌,你可以通过库api和缓存得到很好的干净的syntex。

我在博客上写了这篇文章 http://manan-vaghasiya.in/post/integrating-your-node.js-app-with-google-apis