Nodejs twitter api不返回预期的令牌

时间:2016-02-13 14:42:36

标签: node.js api httprequest twitter-oauth node-request

我正在使用nodejs获取持票人令牌,我的代码看起来像

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服务器无法读取授权类型

1 个答案:

答案 0 :(得分:0)

你的问题只是一个错字。在这一行:

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

您正在指定" Content-Type"作为标题的一部分。

当我使用此curl命令发送无效的Content-Type时,我发现您遇到同样的错误:

$ 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>"}