Axios的安装和配置
pnpm install axios
- 封装 axios:配置baseUrl,请求拦截,响应拦截
import axios from "axios";
const service = axios.create({
baseURL: "http://127.0.0.1:8000/api/v1",
timeout: 3 * 1000,
});
service.interceptors.request.use(
(config) => {
const token = localStorage.getItem("token");
if (token) {
config.headers = {
Authorization: "JWT " + token,
};
}
console.log("查看请求头", config.headers);
return config;
},
(error) => {
return Promise.reject(error);
}
);
service.interceptors.response.use(
(response) => {
return response;
},
(error) => {
if (error && error.response) {
switch (error.response.status) {
case 400:
error.message = "错误请求";
break;
case 401:
error.message = "未授权,请重新登录";
break;
case 403:
error.message = "拒绝访问";
break;
case 404:
error.message = "请求错误,未找到该资源";
window.location.href = "/NotFound";
break;
case 405:
error.message = "请求方法未允许";
break;
case 408:
error.message = "请求超时";
break;
case 500:
error.message = "服务器端出错";
break;
case 501:
error.message = "网络未实现";
break;
case 502:
error.message = "网络错误";
break;
case 503:
error.message = "服务不可用";
break;
case 504:
error.message = "网络超时";
break;
case 505:
error.message = "http版本不支持该请求";
break;
default:
error.message = `连接错误${error.response.status}`;
}
} else {
if (JSON.stringify(error).includes("timeout")) {
console.log("服务器响应超时,请刷新当前页");
}
error.message = "连接服务器失败!";
}
console.log(error.message);
console.log(1213);
return Promise.reject(error);
}
);
export default service;
import service from "./requests";
interface Iget {
[propName: string]: any;
}
export function GetHomeAPI<T>(data: Iget) {
return service.get<T>("/mdm/slideinfo/", {
params: data,
});
}
interface ILogin {
username: string;
password: string;
}
export function PostLoginAPI(data: ILogin) {
return service({
method: "POST",
url: "/user/login/auth/",
data,
});
}
Vue中使用
<script setup lang="ts">
import { GetHomeAPI, PostLoginAPI } from './api/api'
interface IgetHome {
"id": number;
"province": string;
"county": string;
"slide_name": string;
"slide_head": string;
"slide_type": string;
"slide_status": number;
"created_time": string;
"is_active": boolean;
"user": number;
}
interface Ilogin {
"token": string
"id": number
"username": string
"role": boolean
}
function getHome() {
GetHomeAPI<IgetHome>({}).then(
(res) => {
console.log(res)
}
).catch()
}
const getAs = async () => {
await GetHomeAPI({ id: 1 }).then(
(res) => {
console.log(res.data)
}
).catch()
}
const login = () => {
PostLoginAPI({
username: "admin",
password: "521",
}).then(
(res) => {
console.log(res.data)
localStorage.setItem("token", res.data.token)
}
).catch()
}
</script>
<template>
<button @click="getHome">getHome</button>
<button @click="getAs">getAs</button>
<button @click="login">login</button>
</template>
<style>
</style>
Django后端配置
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
),
'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
}
JWT_AUTH = {
'JWT_AUTH_HEADER_PREFIX': 'JWT',
'JWT_RESPONSE_PAYLOAD_HANDLER':
'user.utils.jwt_response_payload_handler',
'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=60 * 60 * 3),
'JWT_ALLOW_REFRESH': True,
'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(
days=7
),
}
验证
结合pinia来使用
import { ElMessage } from 'element-plus';
import axios from 'axios';
import { IUser, KEY_USER_ID } from '@/store/modules/useUserStore';
const service = axios.create({
baseURL: 'http://127.0.0.1:8000/api/v1',
timeout: 5 * 1000,
});
service.interceptors.request.use(
(config) => {
try {
const user = JSON.parse(localStorage.getItem(KEY_USER_ID) || '') as IUser;
if (user.token) {
config.headers!['Authorization'] = `JWT ${user.token}`;
}
} catch (e) {}
return config;
},
(error) => {
return Promise.reject(error);
}
);
service.interceptors.response.use(
(response) => {
return response;
},
(error) => {
if (error && error.response) {
switch (error.response.status) {
case 400:
error.message = '错误请求!';
break;
case 401:
error.message = '未授权,请重新登录';
break;
case 403:
error.message = '拒绝访问';
break;
case 404:
error.message = '请求错误,未找到该资源';
window.location.href = '/NotFound';
break;
case 405:
error.message = '请求方法未允许';
break;
case 408:
error.message = '请求超时';
break;
case 500:
error.message = '服务器端出错';
break;
case 501:
error.message = '网络未实现';
break;
case 502:
error.message = '网络错误';
break;
case 503:
error.message = '服务不可用';
break;
case 504:
error.message = '网络超时';
break;
case 505:
error.message = 'http版本不支持该请求';
break;
default:
error.message = `连接错误${error.response.status}`;
}
} else {
if (JSON.stringify(error).includes('timeout')) {
console.log('服务器响应超时,请刷新当前页');
}
error.message = '连接服务器失败!';
}
ElMessage.error(error.message);
return Promise.reject(error);
}
);
export default service;
import { defineStore } from 'pinia';
export interface IUser {
id: number;
username: string;
token: string;
role: string;
email?: string;
}
export const KEY_USER_ID = 'user';
const useUserStore = defineStore({
id: KEY_USER_ID,
state: (): IUser => ({
id: -1,
username: '',
role: '',
email: '',
token: '',
}),
actions: {
setToken(token: string) {
this.$state.token = token;
},
setID(id: number) {
this.$state.id = id;
},
setRole(role: string) {
this.$state.role = role;
},
login(user: Partial<IUser>) {
this.$state = {
...this.$state,
...user,
};
},
},
persist: {
enabled: true,
strategies: [
{
key: KEY_USER_ID,
storage: localStorage,
},
],
},
});
export default useUserStore;
import useUserStore from '@/store/modules/useUserStore';
import { useRouter } from 'vue-router';
const router = useRouter()
const useUser = useUserStore()
const login = () => {
PostLoginAPI({
username: "admin",
password: "521",
}).then(
(res) => {
console.log(res.data)
useUser.login(res.data)
}
).catch()
}