One: AxiOS basics
Create the XMLHttpRequest from the browser
Make an HTTP request from Node.js
Supporting Promise API
Intercept requests and responses
Transform the request and response data
Cancel the request
Automatically convert JSON data
The client supports CSRF/XSRF prevention
Two: Axios encapsulation
The part about wrapping Axios involves some conventions with the back end.
What’s the deal? When we request the interface, the back end will give us a code.
When I was developing, the general convention was
Code: -200 indicates that the login fails. Code: -100 indicates that an error occurs on the interface. Try {} = try{} = try{} = try{} = try{} = try{}catch(){} to avoid errors reported by the interface) code > 0 The interface returns a success value code < 0 The interface returns a failure valueCopy the code
This way, we can do some preprocessing before encapsulating axios by requesting the return value code.
1: Introduces AXIos
import axios, { AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios';
Copy the code
2: Indicates that the request times out
Set the default request timeout by axios.defaults.timeout. For example, if the request exceeds 10s, the user will be notified that the current request has timed out and please refresh.
// Timeout (ms)
axios.defaults.timeout = 2000 * 1000;
Copy the code
3: Set the POST request header
Post request, we need to add a request header, so you can do a default setting here, that is, set post request header as Application/X-wwW-form-urlencoded; charset=UTF-8
// Axios request header
axios.defaults.headers['X-Requested-With'] = 'XMLHttpRequest'
axios.defaults.headers['token'] = localStorage.getItem('token') | |' '
axios.defaults.headers.post['Content-Type'] = 'application/json'
Copy the code
4: Request interception
We can intercept a request before sending it, why intercept it,
What do we intercept requests for?
For example, some requests can be accessed only after the user has logged in, or post requests need to serialize the data we submit. At this point, we can do an interception before the request is sent, so we can do what we want.
// Request interception
axios.interceptors.request.use(
(config: AxiosRequestConfig) = > {
// Do some data validation here.
// Check session, etc.
return config
},
(error: AxiosError) = > {
return error
}
)
Copy the code
5: Response interception
The response interceptor is easy to understand, it’s just the part I talked about at the beginning and the convention between the back end and the response interceptor, which is to have a couple of fixed status codes and perform the corresponding operations as needed.
Of course, the data the server sends back to us, we can do some processing on it before we get it.
For example, the above idea: if the background returns a status code of 200, then the data is returned normally, otherwise we need to make some errors based on the type of the error status code.
In fact, here is the main error unified processing and no login or login expired after the adjustment of a login page operation.
// Response intercept
axios.interceptors.response.use((result: AxiosResponse) = > {
/ / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
// Return mode 1
/*console.log(result); if (result.status === 200) { if (result.data && result.data.code > 0) { return Promise.resolve(result); } else {alert (result. The data. The MSG | | "fail"); return Promise.reject(result); }} else {alert(" network exception "); return Promise.reject(result); } / / * /
/ / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
// Return mode 2
// What did you do before returning the data
// console.log(result);
if (result.data.code < -100)
{
if (result.data.msg)
{
// Call the custom alert
utils.alert(result.data.msg, function () {
window.location.assign('/pc/index');
});
}
return Promise.reject(result.data.data)
}
return result;
}, (err: AxiosError) = > {
utils.alertLoadExec(false);
// What did you do before returning the data
return Promise.reject(err)
})
Copy the code
6: Encapsulates GET, PUT, and POST requests
Request.ts
import axios from "axios";
import qs from "qs";
/** * Encapsulate request mode */
const request =
{
/ * * *@name: Encapsulates the AXIos get method *@desc: describe *@author: camellia
* @email: guanchao_gc@qq.com
* @date: 2020-12-21
* @param Url request connection *@param Params Request parameter *@param Callback callback method */
get(url: string, params: any, callback: any)
{
return new Promise((resolve, reject) = > {
axios
.get(url, {
params: params
})
.then(res= > {
callback ? resolve(callback(res.data)) : resolve(res.data);
})
.catch(err= > {
reject(err);
});
});
},
/ * * *@name: Encapsulates the AXIos POST method *@desc: describe *@author: camellia
* @email: guanchao_gc@qq.com
* @date: 2020-12-21
* @param Url request connection *@param Params Request parameter *@param Callback callback method */
post(url: string, params: any, callback: any)
{
return new Promise((resolve, reject) = > {
axios
.post(url, qs.stringify(params))
.then(res= > {
callback ? resolve(callback(res.data)) : resolve(res.data);
})
.catch(err= > {
reject(err);
});
});
},
/ * * *@name: put Request encapsulation *@author: camellia
* @email: guanchao_gc@qq.com
* @date: 2021-03-01
* @param Url request connection *@param Params Request parameter *@param Callback callback method */
put(url: string, params: any, callback: any)
{
return new Promise((resolve, reject) = > {
axios
.put(url, params)
.then(res= > {
callback ? resolve(callback(res.data)) : resolve(res.data);
}, err= > {
reject(err)
})
})
},
/ * * *@name: Unified processing of errors after a failed request *@author: camellia
* @email: guanchao_gc@qq.com
* @date: 2021-03-08
* @param {Number} Status Status code of the failed request */
errorHandle(status:any, other:any)
{
// Check the status code
switch (status) {
// 401: is not logged in. The login page is displayed
case 401:
// toLogin();
break;
// 403 Token expires
// Clear the token and jump to the login page
case 403:
// tip(' login expired, please log in again ');
// localStorage.removeItem('token');
// store.commit('loginSuccess', null);
setTimeout(() = > {
// toLogin();
}, 1000);
break;
// 404 Request does not exist
case 404:
// tip(' requested resource does not exist ');
break;
default:
console.log(other); }}}export default request;
Copy the code
7: AxiOS encapsulates the complete code
import axios, { AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios';
// Public status file
import { common } from "/@/hooks/common.ts";
// Introduce the public function js file
import utils from "/@/assets/js/public/function";
// The default request is to connect
// axios.defaults.baseURL = "http://xxxx.xxx.xxxx/index.php";
// Timeout (ms)
axios.defaults.timeout = 2000 * 1000;
// Axios requests to enable cookies, enabling cross-domain requests to carry cookies
axios.defaults.withCredentials = true;
// Axios request header
axios.defaults.headers['X-Requested-With'] = 'XMLHttpRequest'
axios.defaults.headers['token'] = localStorage.getItem('token') | |' '
axios.defaults.headers.post['Content-Type'] = 'application/json'
// Request interception
axios.interceptors.request.use(
(config: AxiosRequestConfig) = > {
// Do some data validation here.
// Check session, etc.
return config
},
(error: AxiosError) = > {
return error
}
)
// Response intercept
axios.interceptors.response.use((result: AxiosResponse) = > {
/ / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
// Return mode 1
/*console.log(result); if (result.status === 200) { if (result.data && result.data.code > 0) { return Promise.resolve(result); } else {alert (result. The data. The MSG | | "fail"); return Promise.reject(result); }} else {alert(" network exception "); return Promise.reject(result); } / / * /
/ / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
// Return mode 2
// What did you do before returning the data
// console.log(result);
if (result.data.code < -100)
{
if (result.data.msg)
{
// Call the custom alert
utils.alert(result.data.msg, function () {
window.location.assign('/pc/index');
});
}
return Promise.reject(result.data.data)
}
return result;
}, (err: AxiosError) = > {
utils.alertLoadExec(false);
// What did you do before returning the data
return Promise.reject(err)
})
export default axios
Copy the code
8: Unified API management
Unified API management, I put each single page request into a corresponding file, this use and management more flexible. And there won’t be the same name when many people work together.
Here’s an example:
Api file: articlelist.ts
// Import the common JS file
import request from "/@/hooks/request";
/ * * *@name: Get a list of articles by category *@author: camellia
* @email: guanchao_gc@qq.com
* @date: the 2021-03-01 * /
export const getArticleListByCategory = (data: any) = > request.get("/index.php/article/getArticleListByCategory", data, ' ');
Copy the code
Page file: articlelist.ts
import {
PropType,
ref,
watch,
reactive,
toRefs,
provide,
inject,
} from "vue";
// Introduce the Axios hook
import axios from "/@/hooks/axios.ts";
// Import routes
import { useRouter, useRoute } from "vue-router";
import HelloWorld from "/@/components/HelloWorld.vue";
import Footer from "/@/components/pc/Footer.vue";
import Header from "/@/components/pc/Header.vue";
import Menu from "/@/components/pc/Menu.vue";
import load from "/@/components/pc/loading.vue";
import TopIM from "/@/components/pc/TopIM.vue";
import Drawer from "/@/components/pc/Drawer.vue";
import Pagination from "/@/components/pc/Pagination.vue";
// Import the common JS file
import utils from "/@/assets/js/public/function";
// API interface file
import { getArticleListByCategory } from "/@/api/pc/articleList.ts";
// Public status file
import { common } from "/@/hooks/common.ts";
export default {
name: "articleList".components: {
HelloWorld,
Footer,
Header,
Menu,
load,
TopIM,
Drawer,
Pagination
},
// The first hook function executed by VUE3 syntax
// Setup official document
/ / https://www.vue3js.cn/docs/zh/guide/composition-api-setup.html#
setup(props: any, content: any) {
// Instantiate the route
const router = useRouter();
const route = useRoute();
/ * * *@name: Declares data *@author: camellia
* @email: guanchao_gc@qq.com
* @date: the 2021-01-18 * /
const data = reactive({
showRef: 0.// loading Whether to display
loading: true.// The list of articles
articleList: [].// Number of data pages
articlePage: 0./ / the current page
currentPage: route.query.page ? route.query.page : 1.// Page display page number
dataNum: 7./ / category id
cate_id: route.query.cate_id ? route.query.cate_id : ' '.// Category name
cat_name:' '.// List of categories
categoryList:' './ / subcategories
cate_id_son: route.query.cate_id_son ? route.query.cate_id_son : ' './ / id tags
label_id: route.query.label_id ? route.query.label_id : ' '.// Search string
search: route.query.search ? route.query.search : ' '});/ * * *@name: Listens for changes in search values *@author: camellia
* @email: guanchao_gc@qq.com
* @date: the 2020-12-21 * /
watch(
() = > common.search,
() = > {
data.search = common.search;
data.currentPage = 1;
data.cate_id = ' ';
data.cate_id_son = ' ';
data.label_id = ' '; getData(); });/ * * *@name: loading Display time *@author: camellia
* @email: guanchao_gc@qq.com
* @date: the 2020-12-21 * /
// utils.sleep(1000).then(() => {
// // here's what you need to do after sleep
// data.loading = false;
// common.loading = data.loading;
// });
/ / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
/ * * *@name: Menu * in the upper right corner@author: camellia
* @email: guanchao_gc@qq.com
* @date: 2021-01-15
* @param: param number menu Whether * is displayed@param: Cate Number Displays the article category ID */
const closeMenu = (param: number,cate:string=' ') = > {
// Param is the value passed by the child component
data.showRef = param;
if(cate ! =' ')
{
data.cate_id = cate;
data.currentPage = 1;
data.cate_id_son = ' ';
data.label_id = ' '; getData(); }}const showMenuByChild = (param: number) = > {
data.showRef = param;
// this.$refs.menuShowObj.getSrcList(this.showRef);
}
/ / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
/ * * *@name: Gets the initial data *@author: camellia
* @email: guanchao_gc@qq.com
* @date: the 2021-01-15 * /
const getData = () = > {
// Document: http://www.axios-js.com/zh-cn/docs/
let info = {
page: data.currentPage,
cate_id: data.cate_id,
cate_id_son: data.cate_id_son,
search:data.search,
label_id:data.label_id
};
let param = utils.createRouterParam(info);
data.loading = true;
try {
getArticleListByCategory(param).then(function (response: any) {
data.cat_name = response.cateName;
data.categoryList = response.cateList;
data.articlePage = response.articlePage;
data.articleList = response.articleShow;
data.loading = false;
utils.goToScrollTop();
});
} catch (error) {
utils.alertMsg(2000.'System error');
}
/*axios.get('/index.php/article/getArticleListByCategory', { params: param }) .then(function (response: any) { data.cat_name = response.data.cateName; data.categoryList = response.data.cateList; data.articlePage = response.data.articlePage; data.articleList = response.data.articleShow; data.loading = false; utils.goToScrollTop(); }) .catch(function (error: any) { }); / / * /
}
/ / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
// Initial call
getData();
/ * * *@name: Binds data to the value dataRef *@author: camellia
* @email: guanchao_gc@qq.com
* @date: the 2021-01-10 * /
const dataRef = toRefs(data);
return {
showMenuByChild,
// showMenu ,closeMenu, ... dataRef } } };Copy the code
These are just some of the things I think axios encapsulates.
For good suggestions, please enter your comments below.
Welcome to guanchao.site
Welcome to applet: