1

我正在使用 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 服务器无法读取授权类型

4

1 回答 1

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>"}
于 2016-02-14T20:53:04.500 回答