首页 > 解决方案 > 反应本机获取发布请求不起作用

问题描述

根据 Instagram API,这是一个获取access_token.

curl -F 'client_id=XXXXXX' \
    -F 'client_secret=XXXXXX' \
    -F 'grant_type=authorization_code' \
    -F 'redirect_uri=XXXXXX' \
    -F 'code=XXXXXX' \
    https://api.instagram.com/oauth/access_token

如果我在终端中运行它,我可以获得如下所示的结果:

{
    "access_token": "fb2e77d.47a0479900504cb3ab4a1f626d174d2d",
    "user": {
        "id": "1574083",
        "username": "snoopdogg",
        "full_name": "Snoop Dogg",
        "profile_picture": "..."
    }
}

问题是它不适用于 react-native。

我正在使用此代码在 react-native 上发出发布请求:

fetch('https://api.instagram.com/oauth/access_token', {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    client_id: 'XXXXXX',
    client_secret: 'XXXXXX',
    grant_type: 'authorization_code',
    redirect_uri: 'XXXXXX',
    code: 'XXXXXX'
  }),
})
.then(res => res.json())
.then(obj =>  {
  console.error(obj);
})
.catch((error) => {
  console.error(error);
})

我不断得到回应You must provide a client_id.

我试图为这个请求创建一个可以工作的 jQuery 代码。

$.ajax({
  type: "POST",
  url: "https://api.instagram.com/oauth/access_token",
  data: {
    client_id: 'XXXXXX',
    client_secret: 'XXXXXX',
    grant_type: 'authorization_code',
    redirect_uri: 'XXXXXX',
    code: 'XXXXXX'
  },
  success: function(html) {
    console.error(html)
  },
  error: function(html) {
    console.error(html)
  }
});

一个也可以工作的单行红宝石代码

Net::HTTP.post_form(URI.parse('https://api.instagram.com/oauth/access_token'), {'client_id': 'XXXXXX','client_secret': 'XXXXXX','grant_type': 'authorization_code','redirect_uri': 'XXXXXX','code': 'XXXXXX'}).body

你能看出我的代码有什么问题吗?它确实适用于 jQuery。

标签: javascriptajaxreact-native

解决方案


推荐阅读