创建server.tsx文件
import axios from 'axios'; import { history, Link } from 'umi'; import { Alert, Space } from 'antd'; const instance = axios.create({ baseURL: '/api', }); // 添加请求拦截器 instance.interceptors.request.use( config => { // 添加 token const token =localStorage.getItem("token") console.log('token :>> ', token); if (token) { config.headers.Authorization = ` ${token}`; console.log('config.headers.Authorization :>> ', config.headers.Authorization); }else{ history.push('/login') } // console.log('config :>> ', config); return config; }, error => { // 处理请求错误 return Promise.reject(error); } ); export default instance;
login.tsx文件中,引入调用,触发拦截器
import React from 'react' import "./login.less" import { LockOutlined, UserOutlined } from '@ant-design/icons'; import { Button, Checkbox, Form, Input } from 'antd'; import axiosed from "@/pages/server" import { history } from 'umi' export default function Login() { const onFinish = async (values: any) => { console.log('Received values of form: ', values); let { data } = await axiosed.post("http://localhost:3020/login", values) if (data.code == 200) { localStorage.setItem("token",data.token) history.push({ pathname: "/home", query: { id: "1" }, state: { con: "你好" } }) } console.log('data :>> ', data.token); };