gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 08:25:02 26 4
gpt4 key购买 nike

我正在使用“axios”:“^0.23.0”,以及 ReactJs 和 Typescript。

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

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

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);
}
)

工具.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;
}
}

索引.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>
)
}

谢谢!

最佳答案

分配 token 值的方式必须改变。变化:

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);
}
);

关于reactjs - 使用 axios 拦截器和响应时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69636830/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com