2014-04-01 2 views
1

Google 드라이브에 파일을 나열하려고합니다.Google 드라이브 - 파일 목록 - 자바 스크립트

나는 이것을 성공하지 못한 채 몇 주간 계속 해왔다. 나는 PHP를 시도 해왔다. 이제 Javascript로 옮겨 어떤 예제를 얻을 수 있는지 알아 보았다.

내가

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

그래서 내가 업로드 한 내 파일의 떨어져 일하고 있어요 예입니다, 올바른 범위가 클라이언트의 비밀, 클라이언트 ID를 가지고, 내 Google 콘솔에서 드라이브 API를 사용할 수

내 계정으로 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

,536,913,632 10
{ 
"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

첫 번째로, 나는 당신이 동적 일 수도 있고 같지 않은 opensshift env 변수를 사용하고있는 것을 볼 수 있습니다.

둘째, 당신은 당신이 동의 화면에 액세스 할 수 있도록 처음 얻을 refresh_token도를 저장하지 않는, 어쩌면 access_token은 당신이 내가 구글 API를 액세스하기위한 google-api-nodejs-client를 사용하는 것이 좋습니다, 그러나 그 refresh_token도

을 사용하여 새로 고침이 너무 만료 , 그것의 공식 google apis 클라이언트 도서관.

이 라이브러리를 사용하면 만료 된 액세스 토큰을 새로 고칠 필요가 없으며 라이브러리 apis와 캐싱을 통해 멋진 깨끗한 신텍스를 얻을 수 있습니다.

관련 문제