方式一: 各API封装为单独的函数
在package.json中为baseUrl添加proxy (React适用)
"proxy": "https://www.xxxx.com/",
封装API
import axios from 'axios'
const baseUrl = '/api/notes'
let token = null
const setToken = newToken => {
token = `bearer ${newToken}`
}
const getAll = async () => {
const response = await axios.get(baseUrl)
return response.data
}
const create = async newObject => {
const config = {
headers: { Authorization: token },
}
const response = await axios.post(baseUrl, newObject, config)
return response.data
}
const update = async (id, newObject) => {
const response = await axios.put(`${ baseUrl } /${id}`, newObject)
return response.data
}
export default { getAll, create, update, setToken }
方法二: 封装为一个全能函数
import axios from 'axios'
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
axios.defaults.baseURL = 'http://xxx.com'
axios.defaults.withCredentials = true // 跨域
export default function request(url: string, type='GET', data={}){
return new Promise((resolve, reject) => {
const option:any = {
url,
method: type,
validateStatus(status:number) {
return (status >= 200 && status < 300) || status === 400
}
}
if (type.toLowerCase() === 'get') {
option.params = data
} else {
option.data = data
}
axios(option).then((res: { status: number; data: unknown }) => {
if(res.status === 200) {
resolve(res.data)
} else {
reject(res.data)
}
}).catch(() => {
console.error({msg: '网络异常'})
reject({msg: '网络异常'})
})
})
}
方法三
创建实例instance, 传入配置
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
之后再调用方法:instance.get/post/put/patch…