2016-02-13 26 views
1

我使用的NodeJS獲得承載令牌我我的代碼看起來像的NodeJS Twitter的API不會返回預期令牌

var fs = require("fs"); 
var https = require("https"); 
var querystring = require("querystring"); 
var bearer = "cunsomer_key:cunsomer_secret" 
var base64ed = new Buffer(bearer).toString("base64"); 

var options = { 
    port: 443, 
    hostname: "api.twitter.com", 
    path: "/oauth2/token", 
    method: "post", 
    headers: { 
     Authorization: "Basic " + base64ed, 
     "Content-Type": "Content-Type: application/x-www-form-urlencoded;charset=UTF-8", 
     "User-Agent": "socialginie" 
    }, 
    key: fs.readFileSync("./testssl.key"), 
    cert: fs.readFileSync("./testcert.cert"), 
} 

var req = https.request(options, res => { 
    res.on("data", d => { 
     console.log(d.toString()); 
    }) 
}) 
req.on("error", e => { 
    console.log(e); 
}); 
req.write(querystring.stringify({ 
    "grant_type": 'client_credentials' 
})) 
req.end(); 

來自API的預期收益是我的承載令牌,並將其在郵遞員應用程序,但在這裏這樣做我得到的錯誤{"errors":[{"code":170,"message":"Missing required parameter: grant_type","label":"forbidden_missing_parameter"}]}

有沒有人有任何想法,爲什麼API服務器無法讀取交付式

回答

0

你的問題只是一個錯字。在這條線:

"Content-Type": "Content-Type: application/x-www-form-urlencoded;charset=UTF-8", 

您指定「內容類型」爲標題的一部分。

當我使用這個curl命令,發送您的無效內容類型,我看到了同樣的錯誤,你這樣做:

$ curl --data "grant_type=client_credentials" -H "Authorization: Basic <credentials-omitted>" -H "Content-Type:" -H "Content-Type: Content-Type: application/x-www-form-urlencoded;charset=UTF-8" https://api.twitter.com/oauth2/token 
{"errors":[{"code":170,"message":"Missing required parameter: grant_type","label":"forbidden_missing_parameter"}]} 

如果我糾正頭,我得到令牌:

$ curl --data "grant_type=client_credentials" -H "Authorization: Basic <credentials-omitted>" -H "Content-Type:" -H "Content-Type: application/x-www-form-urlencoded;charset=UTF-8" https://api.twitter.com/oauth2/token 
{"token_type":"bearer","access_token":"<token-omitted>"}