建立api文件夹,文件夹下有两个文件:index.ts和network.ts文件
//network.ts
import axios from 'axios'
// (1)进行一些全局配置,配置基本请求路径
axios.defaults.baseURL = 'http://127.0.0.1:7001';
axios.defaults.timeout = 5000;
axios.defaults.withCredentials = true; // 让axios发送请求的时候带上cookie
// (2)添加请求拦截器和相应拦截器
axios.interceptors.request.use(function (config) {
// 在发送请求之前做些什么
return config
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error)
})
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
// 对响应数据做点什么
return response
}, function (error) {
// 对响应错误做点什么
return Promise.reject(error)
})
// (3)封装自己的get/post方法,封装成只用传递path和data两个参数,返回的成功状态或失败状态的Promise
export default {
get: function (path = '', data = {}) {
return new Promise(function (resolve, reject) {
axios.get(path, {
params: data
})
.then(function (response) {
resolve(response.data)
})
.catch(function (error) {
reject(error)
})
})
},
post: function (path = '', data = {}) {
return new Promise(function (resolve, reject) {
axios.post(path, data)
.then(function (response) {
resolve(response.data)
})
.catch(function (error) {
reject(error)
})
})
},
all: function (list:any[]) {
return new Promise(function (resolve, reject) {
axios.all(list)
.then(axios.spread(function (...result) {
// 两个请求现在都执行完成
//注意这里用...result去接收参数,因为参数是
// f(a,b)这种形式,那么我们用...result去接收,
//result就是数组形式了[a,b]
resolve(result)
}))
.catch(function (err) {
reject(err)
})
})
}
}
//index.ts
import Network from './network';
//这个索引文件,会对自己的get/post方法再进行一层封装,使得最终效果是注册的时候,只需要调用自己封装的函数,然后只用传递data
//一个参数
export const registerUser = (data:{})=>Network.post('/register', data);