2014-08-29 31 views
1

我試過在普通Node.js中使用Dropbox Core API。Dropbox token API在Node.js中返回「Missing client credentials」

已設定爲:

  1. 用戶打開頁面授權和獲取代碼。
  2. 用戶將代碼輸入到應用程序。
  3. 應用程序將其發送到Dropbox API。
  4. API返回令牌。

但我不能令牌和API返回錯誤消息「缺少客戶端憑據」。

我應該如何寫代碼來獲得令牌?

謝謝。

編輯從鏈接的要點添加代碼:

// About API: 
// https://www.dropbox.com/developers/core/docs#oa2-authorize 
// https://www.dropbox.com/developers/core/docs#oa2-token 

var config = require('./config.json'); 
// OR... 
// var config = { 
// 'appKey': 'xxxxxxxxxxxxxxx', 
// 'secretKey': 'xxxxxxxxxxxxxxx' 
// }; 

var readline = require('readline'); 
var https = require('https'); 
var querystring = require('querystring'); 

// Show authrize page 
var url = 'https://www.dropbox.com/1/oauth2/authorize?' + 
    querystring.stringify({ response_type:'code', client_id:config.appKey }); 
console.log('Open and get auth code:\n\n', url, '\n'); 

// Get the auth code 
var rl = readline.createInterface(process.stdin, process.stdout); 
rl.question('Input the auth code: ', openRequest); // defined below 

function openRequest(authCode) { 
    var req = https.request({ 
     headers: { 'Content-Type': 'application/json' }, 
     hostname: 'api.dropbox.com', 
     method: 'POST', 
     path: '/1/oauth2/token' 
    }, reseiveResponse); // defined below 

    // ################################ 
    // Send code 
    // (maybe wrong...) 
    var data = JSON.stringify({ 
     code: authCode, 
     grant_type: 'authorization_code', 
     client_id: config.appKey, 
     client_secret: config.secretKey 
    }); 
    req.write(data); 
    // ################################ 
    req.end(); 

    console.log('Request:'); 
    console.log('--------------------------------'); 
    console.log(data); 
    console.log('--------------------------------'); 
} 

function reseiveResponse(res) { 
    var response = ''; 
    res.on('data', function(chunk) { response += chunk; }); 

    // Show result 
    res.on('end', function() { 
     console.log('Response:'); 
     console.log('--------------------------------'); 
     console.log(response); // "Missing client credentials" 
     console.log('--------------------------------'); 
     process.exit(); 
    }); 
} 

回答

1

你的這部分代碼是錯誤的:

var data = JSON.stringify({ 
    code: authCode, 
    grant_type: 'authorization_code', 
    client_id: config.appKey, 
    client_secret: config.secretKey 
}); 
req.write(data); 

你發送一個JSON編碼的身體,但API要求形式編碼。

我個人建議使用像request這樣的更高級別的庫,以便於發送表單編碼的數據。 (請參閱我在此處使用的:https://github.com/smarx/othw/blob/master/Node.js/app.js。)

但是,您應該可以在此處使用查詢字符串編碼。只是querystring.stringify替換JSON.stringify

var data = querystring.stringify({ 
    code: authCode, 
    grant_type: 'authorization_code', 
    client_id: config.appKey, 
    client_secret: config.secretKey 
}); 
req.write(data); 
+0

我固定我的代碼使用'querystring.stringify()'和'頭:{ '內容類型': '應用程序/ X WWW的形式,進行了urlencoded'}'。然後服務器響應我的access_token。謝謝你回答我! – Ginpei 2014-08-31 00:53:10

相關問題