【问题标题】:Problem with API of Twitch with Axios GET POST使用 Axios GET POST 的 Twitch API 出现问题
【发布时间】:2021-09-25 14:29:39
【问题描述】:

我遇到了代码问题。

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-native api axios twitch twitch-api


    【解决方案1】:

    显然 API 通过 URL 接收参数,因此将它们作为 url 传递也很有趣。 例如:axios({ 方法:'发布', 网址:'https://id.twitch.tv/oauth2/token?client_id=${variable.a}&client_secret=${variable.b}...

    【讨论】:

      【解决方案2】:

      对于 axios,您需要发送为 data 而不是 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 post request to send form data 和:https://github.com/axios/axios/issues/318

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

      就我个人而言,我使用的是got 而不是axios,所以我发送了

                  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
      

      【讨论】:

        猜你喜欢
        • 2021-05-16
        • 1970-01-01
        • 2019-03-15
        • 1970-01-01
        • 2020-11-08
        • 2020-02-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多