【问题标题】:I'm trying to make a POST request to get receive access token, however I'm receiving undefined. How can I resolve this please?我正在尝试发出 POST 请求以获取接收访问令牌,但是我收到未定义的。请问我该如何解决?
【发布时间】:2020-07-04 04:42:06
【问题描述】:

我正在尝试发出一个 POST 请求来接收访问令牌,但是该函数没有返回任何内容,并且我得到了未定义。请问这个怎么解决?

function getOAuth() {
    fetch("https://accounts.spotify.com/api/token", {
      method: "POST",
      body:
        "grant_type=client_credentials&client_id=" +
        clientId +
        "&client_secret=" +
        clientSecret,
      headers: {
        "Content-Type": "application/x-www-form-urlencoded"
      }
    })
      .then(resp => resp.json()
        // Return the response as JSON
      )
      .then(function(data) {
        // Log the API data
        console.log("token", data);

        // Store token data
        let token = {
          token: data.access_token,
          tokenType:data.token_type,
          expires: new Date().getTime() + data.expires_in * 1000
        }
        return token
      })
      .catch(function(err) {
        // Log any errors
        console.log("something went wrong", err);
      });
  }```

【问题讨论】:

  • 你从哪里得到undefined
  • 您的console.log("token", data) 中是否未定义数据?还是整个get0Auth 函数返回未定义?
  • 没有,当我使用 console.log(data) 时,我得到了响应。但是当我调用它时,函数本身返回未定义
  • 啊,我明白了。我认为这是一个异步问题。答案贴在下面。

标签: javascript reactjs api post fetch


【解决方案1】:

该功能看起来不错,我认为问题在于对服务器的请求。可能 URL 或 post 请求的正文或标头有一些错误。也许这也类似于将mode: 'cors' 添加到您的帖子请求中。遗憾的是,我不知道 spotify api 是否足以帮助您解决这个问题。

【讨论】:

    【解决方案2】:

    函数中没有return语句,就这样添加:

    return fetch("https://accou...
    

    然后就可以用async/await调用函数了

    const token = await getOAuth();
    

    或使用旧的then() 样式

    getOAuth().then(token => console.log(token));
    

    【讨论】:

      【解决方案3】:

      可能发生的情况是该函数下方的代码在完成之前被调用。你可以使用 async 和 await 来强制这个函数下面的代码等待它完成。

      像这样重新定义你的函数:

      async function getOAuth() {
      ...code here
      }
      

      那么在使用函数的时候,这样使用:

      const token = await get0Auth();
      

      【讨论】:

        猜你喜欢
        • 2021-11-03
        • 1970-01-01
        • 1970-01-01
        • 2019-12-16
        • 1970-01-01
        • 2022-12-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多