原生js Vue React axios封装api

tech2022-08-17  138

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({ // baseURL: 'https://newbookstoreapi.shuqireader.com/bookstore/miniapp', timeout: 99999, headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', }, }) // 请求拦截器 service.interceptors.request.use( config => { let token = ''; // document.cookie.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 => { // 如果想提示 后台返回message 参数error.response.data.message 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',//miniapp method: 'post', data: { authCode: "xxx", channelId: "xxx", osName: "xxx", osVer: "xxx", page: "home", platform: 0, userId: 8000000 }, }) </script>

vue React :export default service导出。import 导入就可以了。范式就要你们自行决定了。

最新回复(0)