Axios默认令牌未设置

bd1hkmkf  于 2022-11-05  发布在  iOS
关注(0)|答案(1)|浏览(182)

使用axios,我尝试为所有请求设置默认的头授权令牌。但是它没有默认设置,并且对于任何其他API调用,“授权”也没有在头中设置。
这是UseHttp.js,它是一个通用文件

import axios from 'axios';
const axiosClient = axios.create({
    headers: {
        'Content-type': 'application/json',
        'Accept': 'application/json',
    }
});
const UseHttp = (requestConfig) => {
    return axiosClient({
        url: requestConfig.url,
        method: requestConfig.method || 'GET',
        data: requestConfig.body && JSON.stringify(requestConfig.body)
    }).then((response) => {
        if (response.status == 200) {
            return response.data;
        } else {
            throw new Error(response.data.message);
        }
    }).then((data) => {
        return data.data;
    }).catch((error) => {
        return error.message;
    });
};
export const setAuthHeader = (header) => {

    axiosClient.defaults.headers.common['Authorization'] = header;}
export default UseHttp;

登录后,我设置如下标题

import {USER} from './Url';
import UseHttp, {setAuthHeader} from './UseHttp';
/* eslint-disable */
export const LoginApi = async (values) => {
    const requestOptions = {
        user_name: values.username,
        password: values.password
    }
    try {
        let res = await UseHttp({ url : USER.login, method:'POST', body: requestOptions});
        setAuthHeader(res.token);
        return res;
    } catch (err) {
        return err;
    }
}

但是,当我调用任何其他Api头时,Authorization并没有在CountryApi.js所在的位置设置

import UseHttp from './UseHttp';
   import {LANDING} from './Url';

    export const countryList = () => UseHttp({ url: LANDING.get_country_list });

而Country.js是这样的

import {countryList} from '../../../api/CountryApi';
useEffect(() => {
    countryList().then((res) => {
        setallData(res)

    });
}, [locale])
wribegjk

wribegjk1#

这是一个基本的实现,说明了如何使用拦截器在发送请求之前修改请求,并将令牌附加到头部(如果它存储在本地存储中)。

import Axios from "axios";

const axios = Axios.create({
        headers: {
            'Content-type': 'application/json',
            'Accept': 'application/json',
        }
    });

    axios.interceptors.request.use((config) => {
      const token = localStorage.getItem("token");
      if (token) {
        config.headers!.Authorization = `Bearer ${token}`;
      }

      return config;
    });

相关问题