Axios 拦截器来刷新令牌

时间:2021-02-22 05:15:50

标签: javascript

我正在尝试使用 Axios 进行多个 api 调用,我正在创建一个服务类来实现它,我收到了 400 代码状态,带有“invalid_client”标头。这就是我构建服务类的方式(我正在尝试进行 api 调用以 spotify api)

import axios from "axios";
import { Credentials } from './config';

export default class SpotifyService {

  constructor() {
    const spotify = Credentials();  
    this.service = axios.create({
      baseUrl: "https://api.spotify.com/v1/browse",
    });
    this.service.interceptors.request.use(async (config) => {
      const auth = await authentication();
      config.headers.Authorization = `Bearer ${auth.data.access_token}`;
    });
  }

  getCategories = () => {
    return this.service.get("/categories?limit=6");
  };
}

async function authentication() {
  const response = await axios.post(
    "https://accounts.spotify.com/api/token",
    "grant_type=client_credentials",
    {
      "Content-Type": "application/x-www-form-urlencoded",
      Authorization:
        "Basic " + btoa('clientId:clientSecret'),
    }
  );
}

1 个答案:

答案 0 :(得分:1)

问题似乎是您没有正确添加 Authorization 标头值,因为您的行中存在拼写错误:

      config.header.Authorization = `Bearer ${auth.data.access_token}`;

应该是headers,即:

      config.headers.Authorization = `Bearer ${auth.data.access_token}`;