Network request encapsulation of vue and uniapp

Table of contents

1. vue request encapsulation

2. uniapp request encapsulation

1. vue request encapsulation

Create a new request folder under the src folder of the project. The request.js inside is where the encapsulated code is placed. Import it into api.js, and then write the corresponding request.


import axios from "axios"
const instance = axios.create({
    baseURL:process.env.VUE_APP_BASE_API,
    timeout:5000
})
// 设置请求拦截器
instance.interceptors.request.use(config => {
    // console.log("每一次发起请求前,都会先执行这里的代码");
    // console.log(config); //config是一个对象:记录了本次请求的配置信息
    let token=localStorage.getItem("token");
    // 在发请求前携带请求头
    if(token){
        config.headers["X-Access-Token"]=token;
    }
    return config
}, err => {
    return Promise.reject(err)
})
// 设置响应拦截器:对服务器响应回来的数据做统一处理
instance.interceptors.response.use(res=>{
    // console.log("每一次接收到响应,都会先执行这里的代码,再去执行成功的那个回调函数then");
    // res :是一个对象:原先说的axios封装的res对象
    return res
},err=>{
    return Promise.reject(err)
})
 
export default instance

After being introduced into api.js, the request is written as follows; import instance from './request'

Example get method:

export const GetIMg = (params) => instance.get('/sys/oss/file/getOOSUrl',params)

Example post method:

export const   postNewCopy= (params) => instance.post(`/h5/activiti_process/getProcessNode?id=${params.id}`)

Write the network header in .env.development and .env.production : VUE_APP_BASE_API = "xxx"

2. uniapp request encapsulation

The file is placed in the same place as Vue, but the syntax is different, but the references are consistent!


const $request = (url, data, method = 'POST', headers = "application/json;") => {
	return new Promise((resolve, reject) => {
		uni.showLoading({
			title: '数据加载中',
			icon: 'loading',
			mask: true
		});
		let token= uni.getStorageSync("token")
		uni.request({
			url: 'xxx/api' + url,
			method: method,
			data: data,
			header: {
				'Content-Type': headers,
				'X-Access-Token': token
			},
			success(res) {
				resolve(res)
				uni.hideLoading(); //关闭loading
			},
			fail(error) {
				reject(error);
				uni.hideLoading(); //关闭loading
			},
			complete() {
				uni.hideLoading(); //关闭loading
			}
		})
	})
}
//get请求
const $get = (url, data) => {
	return $request(url, data, 'GET')
}
//post请求
const $post = (url, data) => {
	return $request(url, data, 'POST')
}
//给uniapp原生的requset赋值
//记得要在mian.js中引用
uni.$request = $request
uni.$get = $get
uni.$post = $post

After being introduced into api.js, the request is written as follows;

Example get method:

export const GetIMg = (params) => uni.$get('/sys/oss/file/getOOSUrl',params)

Example post method:

export const   postNewCopy= (params) => uni.$post(`/h5/activiti_process/getProcessNode?id=${params.id}`)

Note: Be sure to introduce it in main.js : import '@/utils/request.js'

Guess you like

Origin blog.csdn.net/qq_44930306/article/details/129266397