首页 > 解决方案 > 使用 Axios GET POST 的 Twitch API 出现问题

问题描述

我遇到了代码问题。

axios({
        method: 'post',
        url: 'https://id.twitch.tv/oauth2/token',
        body: {
        client_id: 'a',
        client_secret: 'Bearer b',
        grant_type: 'client_credentials',}
            }).then(response => {
        console.log(response);

      })
      .catch(error => {
        console.log(error);
      })

结果是:

data: { status: 400, message: 'missing client id' }

但是如果我把它们放在 url 中,这种方式效果很好:

url: 'https://id.twitch.tv/oauth2/token?client_id=a&client_secret=b&grant_type=client_credentials',

我的问题是什么?你也可以给我一个 axios.get 的例子吗?和 :

url: 'https://api.twitch.tv/helix/games/top'
headers: {
client_id: 'a',
Authorization: 'Bearer b',
}

标签: react-nativeapiaxiostwitchtwitch-api

解决方案


data对于axios,您需要发送body

然后构造/发送一个 FormData

所以例如

axios({
  method: "post",
  url: "myurl",
  data: bodyFormData,
  headers: { "Content-Type": "multipart/form-data" },
})
  .then(function (response) {
    //handle success
    console.log(response);
  })
  .catch(function (response) {
    //handle error
    console.log(response);
  });

另请参阅:axios 发布请求以发送表单数据 和:https ://github.com/axios/axios/issues/318

body由于库(axios)不知道如何对发送的数据进行编码,因此使用会得到不同的结果

就我个人而言,我正在使用gotaxios所以我发送

            got({
                url: "https://id.twitch.tv/oauth2/token",
                method: "POST",
                headers: {
                    "Accept": "application/json"
                },
                form: {
                    client_id: config.client_id,
                    client_secret: config.client_secret,
                    grant_type: "client_credentials"
                },
                responseType: "json"
            })
            .then(resp => {
                //SNIP

推荐阅读