使用请求库axios

发起请求

//推荐使用这种写法,或者使用axios.request,不推荐使用axios.get .post .delete的写法,因为get,post,delete和函数签名不太一样

axios({
	url:'/api/util/test',
	method:'get',//默认是get,不区分大小写
	params:{//get请求参数 ?page=1&size=1
		page:1,
		size:1		
	},
	data:object|string|formdata,//请求体,支持多种格式,不同格式的数据会设置不同的Content-Type
	//栗子:常见的几种格式
		data:'name=xiaoming&password=123',  // content-type application/x-www-form-urlencode
		data:formdata, //content-type: "multipart/form-data; boundary=----WebKitFormBoundaryD6YEv53zfeHetQIn"
		data:{name:xiaoming,password:123}  //  content-type application/json
	
})
axios.request()

注意:

如果在axios的基础上又封装了一层,请求时使用axios的实例进行请求

//定义实例 http.js
let instance=axios.create({baseURL:'/corp-api'})
export default instance

//使用
import http from 'http.js'
http({
	url:'/province'
})

请求统一管理

为方便请求复用和管理,所有的接口请求统一放到src/api目录下面,目录组织如下:

api

定义请求

在每个文件中,定义发送的请求

//util.js
import http from './http'

/**
 * 获取音量大小
 * @param {*} materialId
 */
const getVolume = materialId =>
    http.post('/material/getVolumeDB', {
        materialId
    })

/**
 * 图片裁剪
 */
const photoCut = params => http.post('/material/croppicture', params)

export const UTIL_API = {
    getVolume,
    photoCut,
}

在需要用到的文件中调用请求,推荐使用async/await的写法

//xxx.vue
				async fetchTest() {
            const res = await UTIL_API.getVolume()
            console.log('fetchTest -> res', res)
            const res1 = await UTIL_API.photoCut()
            console.log('fetchTest -> res1', res1)
        }

发送请求

在需要发送请求的文件中引入UTIL_API,发送请求: