Use axios to encapsulate uniapp network requests (request interception and request response)

1. First open the root directory of the project where axios needs to be configured, and then open the HBuilderX terminal at this project location to download axios (as shown in the figure:)

Naming of the terminal window: npm install axios

2. Create a folder in the root directory to store files that encapsulate network requests (or create files directly), and the project files are in the utils folder (as shown in the figure)

3. Configure request interception and request response interception according to the official website of axios (Axios usage address: basic use case | Axios Chinese document | Axios Chinese website ), the specific code is as follows

import Vue from 'vue'   //需要先引入vue
import axios from 'axios'  //引入axios
const service = axios.create({
// url = base url + request url
	baseURL: 'http://yqdh.test.site.ximengnaikang.com/pap/api', 
	timeout: 6000, // request timeout
	crossDomain: true  //允许跨域
})
// request拦截器,在请求之前做一些处理
service.interceptors.request.use(
	config => {
	  if (uni.getStorageSync('login_token')) {
		 // 给请求头添加user-token 这块看你使用什么方式存储,需要确定是否有其他关键字
		 config.headers["Authorization"] = `Bearer ${uni.getStorageSync('login_token')}`;
	   }
		console.log('此时请求拦截成功')
		return config;
	},
	error => {
		console.log(error); // for debug
		return Promise.reject(error);
	}
);

//配置成功后的拦截器
service.interceptors.response.use(res => {
//此处一定要打印,因为不同后端给的接口数据格式可能不一样
	console.log(res,'相应拦截了')
	if (res.status == 200) {
		console.log('相应拦截了200')
		return res.data
	} else {
		console.log('相应拦截了非200')
		return Promise.reject(res.data.msg);
	}
}, error => {
	console.log('相应拦截了直接错误')
	if (error.response.status) {
		switch (error.response.status) {
			case 401:
				break;
			default:
				break;
		}
	}
	return Promise.reject(error)
})
export default service

4. After the above configuration is completed, it needs to be hung globally in main.js (convenient to call)

 5. Page usage (get request)

 6. Page usage (post request)

 

Guess you like

Origin blog.csdn.net/weixin_44191318/article/details/125378123