encapsulation axios: To configure baseUrl, Request to intercept , The response to intercept
// requests.ts In file
// import { Message } from "element-ui";
/**** request.js ****/
// Import axios
import axios from "axios";
// Use element-ui Message Make a message reminder
//1. Create a new axios example ,
const service = axios.create({
// Public interface -- Note here that we will talk about
baseURL: "http://127.0.0.1:8000/api/v1",
// Timeout time The unit is ms, I've set it up here 3s Timeout for
timeout: 3 * 1000,
});
// 2. Request interceptor
service.interceptors.request.use(
(config) => {
// Some processing before sending a request , Data transformation , Configure the request header , Set up token, Set up loading etc. , Add... As needed
// config.data = JSON.stringify(config.data); // Data transformation , You can also use qs transformation
// config.headers = {
// "Content-Type": "application/x-www-form-urlencoded", // Configure the request header
// };
// Pay attention to token We need to introduce cookie Method or use local localStorage Other methods , recommend js-cookie
const token = localStorage.getItem("token"); // Here take token Before , You definitely need to get token, Save it
if (token) {
// config.params = { token: token }; // If required, carry it in the parameter
config.headers = {
// Need basis DRF Provided JWT Certified to carry Token, The prefix can also be something else
Authorization: "JWT " + token,
}; // If the request is carried in the request header
}
console.log(" Check the request header ", config.headers);
return config;
},
(error) => {
return Promise.reject(error);
}
);
// 3. Response interceptors
service.interceptors.response.use(
(response) => {
// Some common processing after receiving the response data and successfully , close loading etc.
return response;
},
(error) => {
/***** The processing of abnormal response is started *****/
if (error && error.response) {
// 1. Common error handling
// 2. Handle according to the response code
switch (error.response.status) {
case 400:
error.message = " Wrong request ";
break;
case 401:
error.message = " unauthorized , Please login again ";
break;
case 403:
error.message = " Access denied ";
break;
case 404:
error.message = " Request error , The resource was not found ";
window.location.href = "/NotFound";
break;
case 405:
error.message = " The request method does not allow ";
break;
case 408:
error.message = " request timeout ";
break;
case 500:
error.message = " Server side error ";
break;
case 501:
error.message = " Network not implemented ";
break;
case 502:
error.message = " Network error ";
break;
case 503:
error.message = " Service not available ";
break;
case 504:
error.message = " Network timeout ";
break;
case 505:
error.message = "http The version does not support the request ";
break;
default:
error.message = ` Connection error ${
error.response.status}`;
}
} else {
// timeout handler
if (JSON.stringify(error).includes("timeout")) {
console.log(" Server response timed out , Please refresh the current page ");
}
error.message = " Failed to connect to server !";
}
// Can cooperate with Element-plus To prompt relevant information
// ELMessage.error(error.message);
/***** End of processing *****/
// If no error handling is required , The above processes can be omitted
// return Promise.resolve(error.response);
console.log(error.message);
console.log(1213);
return Promise.reject(error);
}
);
//4. Import files
export default service;
ts Simple use in ,get and post request
// api.ts
import service from "./requests";
// Export each... As needed API
// *************************** //
// Request home page data
interface Iget {
[propName: string]: any;
}
export function GetHomeAPI<T>(data: Iget) {
return service.get<T>("/mdm/slideinfo/", {
...data });
}
interface ILogin {
username: string;
password: string;
}
export function PostLoginAPI(data: ILogin) {
return service({
method: "POST",
url: "/user/login/auth/",
data,
});
}
# settings.py
# in the light of drf Configuration information , Global configuration drf Authentication and permissions of the view
REST_FRAMEWORK = {
# Specify view permissions
'DEFAULT_PERMISSION_CLASSES': (
# 'rest_framework.permissions.AllowAny', # By default, each view , Allow any user to access
# 'rest_framework.permissions.IsAuthenticatedOrReadOnly', # The authenticated user can operate , Otherwise, you can only access
'rest_framework.permissions.IsAuthenticated', # The authenticated user can operate , Otherwise, you can only access
), # You can also specify permission classes in each view
# Appoint drf Authentication mechanism
'DEFAULT_AUTHENTICATION_CLASSES': (
# rest_framework_jwt authentication , You can also specify the authentication class in each view
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
),
# new edition drf schema_class The default is rest_framework.schemas.openapi.AutoSchema
'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
}
# Global configuration drf Current limiting of the view Throttling
# REST_FRAMEWORK = {
# 'DEFAULT_THROTTLE_CLASSES': (
# # Restrict all anonymous unauthenticated users , Use IP Differentiate users
# 'rest_framework.throttling.AnonRateThrottle',
# # Restrict authenticated users , Use User id To distinguish between
# 'rest_framework.throttling.UserRateThrottle'
# ),
# 'DEFAULT_THROTTLE_RATES': {
# # have access to second, minute, hour or day To indicate the period
# 'anon': '3/minute',
# 'user': '5/minute'
# }
# }
# in the light of rest_framework_jwt Configuration information
JWT_AUTH = {
'JWT_AUTH_HEADER_PREFIX': 'JWT', # Set up Prefix in the request header
'JWT_RESPONSE_PAYLOAD_HANDLER':
# 'rest_framework_jwt.utils.jwt_response_payload_handler', # Default jwt Authentication successful return data
'user.utils.jwt_response_payload_handler', # Customize jwt Authentication successful return data
'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=60 * 60 * 3), # To specify token The validity of the , Default 5 branch
'JWT_ALLOW_REFRESH': True, # Allow refresh
'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(
days=7
), # How often can the old be used token To refresh to get new token, The default is 7 God
}
verification
Not logged in
Before login , No, token etc.
After logging in , Save the token
After logging in , Re request data
combination pinia To use
Change request interception
import {
ElMessage } from 'element-plus';
// Import axios
import axios from 'axios';
import {
IUser, KEY_USER_ID } from '@/store/modules/useUserStore';
// Use element-ui Message Make a message reminder
//1. Create a new axios example ,
const service = axios.create({
// Public interface -- Note here that we will talk about
baseURL: 'http://127.0.0.1:8000/api/v1',
// Timeout time The unit is ms, I've set it up here 5s Timeout for
timeout: 5 * 1000,
});
// 2. Request interceptor
service.interceptors.request.use(
(config) => {
// Some processing before sending a request , Data transformation , Configure the request header , Set up token, Set up loading etc. , Add... As needed
// config.data = JSON.stringify(config.data); // Data transformation , You can also use qs transformation
// config.headers = {
// "Content-Type": "application/x-www-form-urlencoded", // Configure the request header
// };
// Pay attention to token We need to introduce cookie Method or use local localStorage Other methods , recommend js-cookie
// Here take token Before , You definitely need to get token, Save it
try {
const user = JSON.parse(localStorage.getItem(KEY_USER_ID) || '') as IUser;
if (user.token) {
config.headers!['Authorization'] = `JWT ${
user.token}`;
}
} catch (e) {
}
// if (token) {
// // config.params = { token: token }; // If required, carry it in the parameter
// config.headers = {
// // Need basis DRF Provided JWT Certified to carry Token, The prefix can also be something else
// Authorization: 'JWT ' + token.token,
// }; // If the request is carried in the request header
// }
// console.log(' Check the request header ', config.headers);
return config;
},
(error) => {
return Promise.reject(error);
}
);
// 3. Response interceptors
service.interceptors.response.use(
(response) => {
// Some common processing after receiving the response data and successfully , close loading etc.
return response;
},
(error) => {
/***** The processing of abnormal response is started *****/
if (error && error.response) {
// 1. Common error handling
// 2. Handle according to the response code
switch (error.response.status) {
case 400:
error.message = ' Wrong request !';
break;
case 401:
error.message = ' unauthorized , Please login again ';
break;
case 403:
error.message = ' Access denied ';
break;
case 404:
error.message = ' Request error , The resource was not found ';
window.location.href = '/NotFound';
break;
case 405:
error.message = ' The request method does not allow ';
break;
case 408:
error.message = ' request timeout ';
break;
case 500:
error.message = ' Server side error ';
break;
case 501:
error.message = ' Network not implemented ';
break;
case 502:
error.message = ' Network error ';
break;
case 503:
error.message = ' Service not available ';
break;
case 504:
error.message = ' Network timeout ';
break;
case 505:
error.message = 'http The version does not support the request ';
break;
default:
error.message = ` Connection error ${
error.response.status}`;
}
} else {
// timeout handler
if (JSON.stringify(error).includes('timeout')) {
console.log(' Server response timed out , Please refresh the current page ');
}
error.message = ' Failed to connect to server !';
}
// Can cooperate with Element-plus To prompt relevant information
ElMessage.error(error.message);
/***** End of processing *****/
// If no error handling is required , The above processes can be omitted
// return Promise.resolve(error.response);
return Promise.reject(error);
}
);
//4. export file
export default service;
pinia in
import {
defineStore } from 'pinia';
// Define the interface according to the returned data
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;
},
// Make all interface specifications optional
login(user: Partial<IUser>) {
this.$state = {
...this.$state,
...user,
};
},
},
// Enable data cache to browser
persist: {
enabled: true,
strategies: [
{
// Custom name
key: KEY_USER_ID,
// Save the location , The default is saved in sessionStorage
storage: localStorage,
// Specify the data to persist
// paths: ['age'],
},
],
},
});
export default useUserStore;