从Javascript与REST客户端调用端点时,来自Spotify API的响应有所不同

时间:2019-05-28 23:22:12

标签: javascript rest post

我正在使用Spotify API在项目中实现一些Spotify调用,我要做的第一件事就是进行身份验证。我使用Restlet(一个REST API客户端)测试了Spotify API端点,并且我的调用成功,响应如下:

  

{“ access_token”:   “ BQC2PbOsWsnkfzcMUMW5YeJh9VGgE7uSQ-ubpO5kekyn3IIq0yVqoIW6Rx-5sQLJyH8R8wik6PzcFfzFDCU”   “ token_type”:“承载者”,“ expires_in”:3600,“ scope”:“”}

然后我使用JavaScript在我的React应用中实现了POST调用,并且成功了!

async function getSpAccessToken(component) {
    const [initSpotResponse] = await Promise.all([
        axios.post("https://accounts.spotify.com/api/token",
            querystring.stringify({
                grant_type: 'client_credentials'
            }),
            {
                headers: {
                    'Authorization': `Basic ${encodedString}`,
                    'Content-type': 'application/x-www-form-urlencoded'
                }
            }
        ).catch((error) => {
            console.log("getSpAccessToken ERROR = " + JSON.stringify(error))
        })
    ]);
    const spAccessToken = await initSpotResponse.data.access_token 

}

但是最终,当令牌到期时,我对Spotify的调用会像预期的那样以“ access_token expired”消息进行响应。我回过头来使用相同的getSpAccessToken()函数进行重新认证,但得到的是响应:

{
  "data": "",
  "status": 200,
  "statusText": "OK",
  "headers": {},
  "config": {
    "transformRequest": {},
    "transformResponse": {},
    "timeout": 0,
    "xsrfCookieName": "XSRF-TOKEN",
    "xsrfHeaderName": "X-XSRF-TOKEN",
    "maxContentLength": -1,
    "headers": {
      "Accept": "application/json, text/plain, */*",
      "Content-Type": "application/x-www-form-urlencoded",
      "Authorization": "Basic ZmY1NmFiZTc3OTJmNDI2ZWE0MWE3NzFkNzA3ZDY2OTaA6YjJjY2EyZGVkZDM5NDliMGE2YzVlMTU4MjQ0NmM5YzU="
    },
    "method": "post",
    "url": "https://accounts.spotify.com/api/token",
    "data": "grant_type=client_credentials"
  },
  "request": {}
}

响应令人困惑,因为a)状态码正常,并且b)data字段为空(这是访问令牌所在的位置)。然后,我尝试使用REST客户端Restlet再次尝试相同的调用,并在响应中得到一个access_token!然后返回并刷新页面,调用我的getSpAccessToken()函数,这一次它返回一个数据对象:

{
  "data": {
    "access_token": "BQCuvTWeJlixkOsuAhKPClKWaXTaSPiuycNY6Z2EKKQLqsDyGyXdDcn4RR4tVq6--1HHJ_l1ViDlCi_mN_bk",
    "token_type": "Bearer",
    "expires_in": 3600,
    "scope": ""
  },
  "status": 200,
  "statusText": "OK",
  "headers": {
    "content-type": "application/json"
  },
  "config": {
    "transformRequest": {},
    "transformResponse": {},
    "timeout": 0,
    "xsrfCookieName": "XSRF-TOKEN",
    "xsrfHeaderName": "X-XSRF-TOKEN",
    "maxContentLength": -1,
    "headers": {
      "Accept": "application/json, text/plain, */*",
      "Content-Type": "application/x-www-form-urlencoded",
      "Authorization": "Basic ZmY1NmFiZTc3OTJmNDI2ZWE0MWE3NzFkNzA3ZDY2OaTA6YjJjY2EyZGVkZDM5NDliMGE2YzVlMTU4MjQ0NmM5YzU="
    },
    "method": "post",
    "url": "https://accounts.spotify.com/api/token",
    "data": "grant_type=client_credentials"
  },
  "request": {}
}

我的问题:为什么当我需要刷新令牌时,我的javascript getSpAccessToken()调用会返回带有空data字段的响应,直到使用REST客户端进行相同的调用为止?

0 个答案:

没有答案