【问题标题】:Calling spotify API will give me bad request (using Axios) even with AccessToken即使使用 AccessToken 调用 spotify API 也会给我错误的请求(使用 Axios)
【发布时间】:2017-12-01 02:48:32
【问题描述】:
// If you want your component to get data to render
componentWillMount() {
// Called first time the comp is loaded right before the comp is added to the page
    console.log('Component WILL MOUNT!')

    const BASE_URL = 'https://api.spotify.com/v1/search?';
    const FETCH_URL = 'https://api.spotify.com/v1/artists/0OdUWJ0sBjDrqHygGUXeCF';
    var accessToken = .......


    axios.get(FETCH_URL, {headers : {'Authorization' : accessToken}})

    .then((response) => {

        console.log(response);


    })

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

在我的 React webapp 中,我从我提供的 accessToken 声明的 URL 请求 api。在我指定我的 accessToken 之前,它给了我 401(未经授权的错误),但现在它给了我 400(错误请求)。

我做错了什么?

【问题讨论】:

  • 这是 OAuth2 吗?标题可能不正确。它应该是 Authorization: Bearer [token string] 或类似的。
  • 你的意思是这样的? axios.get(FETCH_URL, {headers : {'Authorization' : Bearer [accessToken]}})
  • 是的,根据 OAuth2 方法,值(冒号后)应该以单词 Bearer 开头,后跟空格,后跟令牌

标签: reactjs api spotify axios


【解决方案1】:

使用下面的代码,它会帮助你。

实际上,你需要基于OAuth2方法,值(冒号后)应该以Bearer开头,后跟空格,后跟token。

如果您看到您的控制台,那么您将收到以下错误响应,

      {
          "error": {
              "status": 400,
              "message": "Only valid bearer authentication supported"
          }
      }

就像@marekful 在评论中添加的一样,有关更多信息,请查看spotify 授权指南到here

      accessToken = 'Bearer' + ......;

      axios.get(FETCH_URL, {headers : {'Authorization' : accessToken}})

      .then((response) => {

          console.log(response);


      })

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

希望对您有所帮助!

【讨论】:

  • 我使用了完全相同的代码,但仍然收到 400 Bad Request。
  • 能否在componentDidMount()方法中调用你的API?
猜你喜欢
  • 2021-07-05
  • 2017-11-04
  • 2022-12-16
  • 1970-01-01
  • 1970-01-01
  • 2021-12-09
  • 2019-08-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多