Dropbox token API在Node.js中返回“Missing client credentials”

我尝试在普通的Node.js中使用Dropbox Core API。

它被编程为:

  1. 用户打开授权页面并获取代码。
  2. 用户将代码input到应用程序。
  3. 应用程序将其发送到Dropbox API。
  4. API返回令牌。

但我不能令牌和API返回错误消息“丢失的客户端凭据”。

  • 我的代码在这里: https : //gist.github.com/ginpei/65890135d323f18207c0
  • 关于API: https : //www.dropbox.com/developers/core/docs

我应该如何编写代码来获取令牌?

谢谢。

编辑从链接的要点添加代码:

// 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(); }); } 

这部分代码是错误的:

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

您正在发送一个JSON编码的正文,但API期望表单编码。

我个人build议使用像request这样的更高级别的库来更容易地发送表单编码的数据。 (见我在这里使用: https : //github.com/smarx/othw/blob/master/Node.js/app.js 。)

但是你应该可以在这里使用查询string编码。 用querystring.stringifyreplaceJSON.stringify

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