1.废话不多说直接上代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>axios封装
</title>
</head>
<body></body>
</html>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.20.0-0/axios.min.js"></script>
<script>
const service = axios.create({
timeout: 99999,
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
},
})
service.interceptors.request.use(
config => {
let token = '';
if(token){
config.headers['Authorization'] = token
}
return config
},
error => {
return Promise.reject(error)
}
)
service.interceptors.response.use(
response => {
const res = response.data
if (res.code != 200 && res.code) {
console.log('失败');
return Promise.reject(new Error(res.message || 'Error'))
} else {
return res
}
},
error => {
if (error && error.response) {
switch (error.response.status) {
case 400:
console.log('请求错误')
break
case 401:
console.log('权限不足,请重新登率')
break
case 403:
console.log('拒绝访问')
break
case 404:
console.log('请求地址出错', error.response.data.message)
break
case 408:
console.log('请求超时')
break
case 500:
console.log('微服务故障, 请稍后再试')
break
case 501:
console.log('服务未实现')
break
case 502:
console.log('网关错误')
break
case 503:
console.log('服务不可用')
break
case 504:
console.log('网关超时')
break
case 505:
console.log('HTTP版本不受支持')
break
default:
}
}
return Promise.reject(error)
}
)
service({
url: 'https://newbookstoreapi.shuqireader.com/bookstore/miniap',
method: 'post',
data: {
authCode: "xxx",
channelId: "xxx",
osName: "xxx",
osVer: "xxx",
page: "home",
platform: 0,
userId: 8000000
},
})
</script>
vue React :export default service导出。import 导入就可以了。范式就要你们自行决定了。
转载请注明原文地址:https://tech.qufami.com/read-2669.html