代码之家  ›  专栏  ›  技术社区  ›  Leff

在Vue项目中使用axios拦截器

  •  0
  • Leff  · 技术社区  · 4 年前

    我有一些组件在它们创建的方法中发出get请求。我正在使用oidc客户端进行授权。我想用从oidc获得的令牌设置每个请求头。我做了一个 http.js 项目根目录下的文件,如下所示:

    import axios from 'axios';
    import AuthService from "./AuthService";
    
    const authService = new AuthService();
    let token;
    
    axios.interceptors.request.use(async function (config) {
        await authService.getUser().then(res => {
            if (res) {
                token = res.id_token;
                config.headers['Authorization'] = `Bearer ${token}`;
            }
        });
    
        // eslint-disable-next-line no-console
        console.log('interceptor', config);
        return config;
    }, function (error) {
        // Do something with request error
        return Promise.reject(error);
    });
    

    我不确定这是否是设置拦截器的方法,以及如何实际使用它们,因为每次请求时,我都会看到它们没有被设置,控制台中也没有记录任何内容。这应该如何设置?

    0 回复  |  直到 4 年前