使用axios拦截器和响应时出错



我正在使用"axios"; "^0.23.0"和ReactJs和Typescript。

我想拦截请求和响应,并添加用户的令牌。

当我尝试使用请求拦截器时,我得到以下错误:

Object is possibly 'undefined'.  TS2532
(property) AxiosRequestConfig<any>.headers?: AxiosRequestHeaders | undefined
(config) => {
const user = getUserLocalStorage();
config.headers.Authorization = user?.token;
^
return config;
},
(error) => {

当我将.Authorization添加到

时发生此错误
config.headers.Authorization = user?.token;

我应该怎么做来修复这个错误?

这些是我使用的方法:

api.ts

import axios from "axios";
import { getUserLocalStorage } from "../context/AuthProvider/util";
export const Api = axios.create({
baseURL: "http://localhost:8000/",
});
Api.interceptors.request.use(
(config) => {
const user = getUserLocalStorage();
config.headers.Authorization = user?.token;
return config;
},
(error) => {
return Promise.reject(error);
}
)

util.ts

import { Api } from "../../services/api";
import { IUser } from "./types";
export function setUserLocalStorage (user: IUser | null) {
localStorage.setItem('u', JSON.stringify(user));
}
export function getUserLocalStorage () {
const json = localStorage.getItem('u');
if (!json) {
return null;
}
const user = JSON.parse(json);
return user ?? null;
}
export async function LoginRequest (username: string, password: string) {
try {
const request = await Api.post(
'login/', 
{username, password}
);
return request.data;
} catch (error) {
return null;
}
}

index.tsx

import React, {createContext, useEffect, useState} from "react";
import { IAuthProvider, IContext, IUser } from "./types";
import { getUserLocalStorage, LoginRequest, setUserLocalStorage } from "./util";
export const AuthContext = createContext<IContext>({} as IContext)
export const AuthProvider = ({children}: IAuthProvider) => {
const [user, setUser] = useState<IUser | null>()
useEffect(() => {
const user = getUserLocalStorage();
if (user) {
setUser(user);
}
}, [])
async function authenticate(
username:string, 
password: string
) {
let response: any;
response = await LoginRequest(username, password);
const payload = {token: response.token};
setUser(payload);
setUserLocalStorage(payload);
}
function logout () {
setUser(null);
setUserLocalStorage(null);
}
return (
<AuthContext.Provider value={{...user, authenticate, logout}}>
{children}
</AuthContext.Provider>
)
}

谢谢!

必须更改令牌值的分配方式。变化:

config.headers.Authorization = user?.token;

为:

config.headers = {
Authorization: user?.token,
};

那么,它应该是这样的:

export const Api = axios.create({
baseURL: "http://localhost:8000/",
});
Api.interceptors.request.use(
(config) => {
const user = getUserLocalStorage();
config.headers = {
Authorization: user?.token,
};
return config;
},
(error) => {
return Promise.reject(error);
}
);

实际上,你不应该在拦截器上重新定义headers对象。

相反,在添加新的授权属性之前,您应该检查headers对象是否存在。

所以,不用这个:

Api.interceptors.request.use(
(config) => {
const user = getUserLocalStorage();
// This might cause issues because the `headers` object is always being redefined here - previously passed headers will be discarded
config.headers = {
Authorization: user?.token,
};
return config;
},
(error) => {
return Promise.reject(error);
}
);

你应该这样做:

Api.interceptors.request.use(
(config) => {
const user = getUserLocalStorage();
if(!config.headers) {
config.headers = {};
}
config.headers.Authorization = user?.token;
return config;
},
(error) => {
return Promise.reject(error);
}
);

这样可以确保您没有忽略/覆盖可能来自axios.{post/get/delete/etc}(url, config)调用的headers对象。

相关内容

  • 没有找到相关文章

最新更新