首页 > 解决方案 > 将 cURL 命令转换为 JavaScript

问题描述

我正在尝试从我的服务器(nodeJS)调用 Instagram API 调用,但我不知道该怎么做。

curl -X POST https://api.instagram.com/oauth/access_token \
  -F client_id=123456... \
  -F client_secret=123abc... \
  -F grant_type=authorization_code \
  -F redirect_uri=https://google.sg/ \
  -F code=123abc

当我在命令行上运行此命令时,它会返回所需的输出,但我似乎找不到在 JavaScript 中执行相同操作的方法。这是我尝试过的:

axios
  .post("https://api.instagram.com/oauth/access_token", {
    client_id: 123456...,
    client_secret: "123abc...",
    grant_type: "authorization_code",
    redirect_uri: "https://google.sg",
    code:
      "123abc...",
  })

这是 catch 块登录的内容:

data: {
  error_type: 'OAuthException',
  code: 400,
  error_message: 'Missing required field client_id'
}

我认为-F是指表单数据,但我似乎无法在 axios 中找到这样做的方法。

编辑:我已经用 just 试过了client_id,它返回了同样的错误。

编辑2:我不认为这是一个修复,但邮递员代理有一个漂亮的功能来将HTTP请求转换为代码: 在此处输入图像描述

可通过Code右侧访问。

标签: node.jsaxios

解决方案


只需在您的 CURL 请求中看到您有 redirect_uri:https://google.sg/

在您的 axios 参数中,您有:https://google.sg

/在 axios 参数中缺少 a 。

Oauth2 的工作方式是将参数附加到您的 api 设置中指定的 redirect_uri ,因此如果您将其设置为https://google.sg/,则预计它确实是相同的 url,没有任何更改。

您应该得到的响应是: https://google.sg/access_token=#xxxx

正如您所指定的,响应会有所不同,如下所示:

https://google.sg?access_token=#xxxx

这不仅是一个无效的 URL,而且与您指定的 URL 不匹配。

因此,建议您设置标准路径,例如:

https://google.sg/oauth

所以最后你会得到:

https://google.sg/oauth?access_token=#xxxx


推荐阅读