2016-02-13 28 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>"}