node.js - Nodejs twitter api 不返回预期的 token

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

我正在使用nodejs来获取不记名 token ,我的代码如下

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 的预期返回是我的不记名 token ,它在 postman 应用程序中这样做,但在这里我收到错误 {"errors":[{"code":170,"message":"Missing required parameter: grant_type","label":"forbidden_​​missing_parameter"}]}

有谁知道为什么 api 服务器无法读取授权类型

最佳答案

您的问题只是一个拼写错误。在这一行:

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

您将“Content-Type”指定为 header 的一部分。

当我使用此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"}]}

如果我更正标题,我会得到一个 token :

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

关于node.js - Nodejs twitter api 不返回预期的 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35381232/

相关文章:

node.js - 没有这样的说明书——OpsWorks 找不到自定义说明书

node.js - 如何在 Vagrant VM 上安装 bcrypt?

javascript - Node.js xml2js 解析器未定义

Node.js 无法通过网络建立连接

node.js - 如何使 typescript 与 promise 一起工作?

swift - 如何将参数 (args) 传递给 `request.get` ?

android - 还有什么我尝试导入 "Unable to resolve target ' android- 出现 8'"错误

javascript - 调用 api 时出现错误已被 CORS 策略阻止

java - 在 Netty 中处理 Http 状态码 302 Moved Temporarily

c - 使用 C 将 HTTP 请求存储在数组中