2016-12-04 9 views
0

им нового в nodejs и EXPECIALLY в клятве так или иначе им следующие googleapis для nodejs и это то, что я DIT, так как в настоящее времяNodejs OAuth ошибка

var fs = require('fs'); 
var readline = require('readline'); 
var google = require('googleapis'); 
var express = require('express'); 
var app = express(); 

var port = 3000; 

var OAuth2 = google.auth.OAuth2; 
var oauth2client; 



app.get('/', function(req, res){ 

    fs.readFile('client_secret.json', function processClientSecrets(err, content) { 
     if (err) { 
      console.log('Error loading client secret file: ' + err); 
      return; 
     } 
     // Authorize a client with the loaded credentials, then call the 
     // Gmail API. 
     var credentials = JSON.parse(content); 
     var clientSecret = credentials.web.client_secret; 
     var clientId = credentials.web.client_id; 
     var redirectUrl = credentials.web.redirect_uris; 

     oauth2client = new OAuth2( 
      clientId, 
      clientSecret, 
      redirectUrl 
     ); 

     var SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']; 

     var info = "Accedi a GMail" 

     var getCode = oauth2client.generateAuthUrl({ 
      // 'online' (default) or 'offline' (gets refresh_token) 
      access_type: 'offline', 

      // If you only need one scope you can pass it as string 
      scope: SCOPES 
     }); 

     res.send(info+"<br><br><button onclick='window.location.href=\""+ getCode +"\"'>Log in</button>"); 

    }); 
}); 


app.get("/code", function(req,res){ 
    var code = req.query.code; 
    res.send(code); 
    oauth2client.getToken(code, function (err, tokens) { 
    // Now tokens contains an access_token and an optional refresh_token. Save them. 
     if (!err) { 
      oauth2Client.setCredentials(tokens); 
      console.log(tokens); 
     } 
     else{ 
      console.log(err); 
     } 
    }); 
}); 

console.log('Server listen in port '+port+'. Connect to localhost'); 
app.listen(port); 

я получить код совершенно , но когда я приезжаю в маркере разделе у меня есть недопустимая ошибка запроса от функции getToken

{ Error: invalid_request 
at Request._callback (C:\Users\Edoardo\node_modules\google-auth-library\lib\ 
transporters.js:81:15) 
at Request.self.callback (C:\Users\Edoardo\node_modules\google-auth-library\ 
node_modules\request\request.js:187:22) 
at emitTwo (events.js:106:13) 
at Request.emit (events.js:191:7) 
at Request.<anonymous> (C:\Users\Edoardo\node_modules\google-auth-library\no 
de_modules\request\request.js:1044:10) 
at emitOne (events.js:96:13) 
at Request.emit (events.js:188:7) 
at IncomingMessage.<anonymous> (C:\Users\Edoardo\node_modules\google-auth-li 
brary\node_modules\request\request.js:965:12) 
at emitNone (events.js:91:20) 
at IncomingMessage.emit (events.js:185:7) code: 400 } 

я просто скопировал его из googleapis страницы Что я делаю не так?

ответ

0

Вы проверили тело ответа? «error» и «error_description» могут предоставить вам более подробную информацию о вашей проблеме. Обычно отсутствуют отсутствующие параметры или код, используемый до этого, чтобы можно было пропустить ошибку. Добавить третий параметр в вашей getToken обратного вызова, как это:

Изменить это в коде для получения тела ответа:

oauth2client.getToken(code, function (err, tokens) { 
    if (!err) { 
     console.log(tokens); 
     console.log(response.body); 
     oauth2Client.setCredentials(tokens); 
     //DO something great 
    } else { 
     console.log(err); 
     console.log(response.body.error); 
     console.log(response.body.error_description); 
     // :(
    } 
}); 

К

//response parameter added 
oauth2Client.getToken(codigo, function (err, tokens,response) { 
    if (!err) { 
     console.log(tokens); 
     console.log(response.body); 
     oauth2Client.setCredentials(tokens); 
     //DO something great 
    } else { 
     console.log(err); 
     console.log(response.body.error); 
     console.log(response.body.error_description); 
     // :(
    } 
}) 

Я была такая же проблема, так что я начал чтобы посмотреть код внутренней библиотеки, и я нашел это. С этим, возможно, вы могли бы найти, в чем проблема. Удачи;)

+0

Параметр MIssing: redirect_uri Что я должен добавить сейчас? – Machine1104

+0

В вашем конструкторе OAtuh2 третьим параметром является перенаправление URL после завершения процесса входа в систему. Что-то вроде этого: \t \t \t вар oauth2Client = новый OAuth2 ( \t \t \t \t \t config.GOOGLE_CLIENT, \t \t \t \t \t config.GOOGLE_SECRET, \t \t \t \t \t 'www.asdfasdf.com/landing.htmll' \t \t \t \t); – hernanBeiza