日结博客 04.19.18 HZ
对于每次都要从页面导入axios和配置路径的行为简直没完没了地厌恶,每次后台修改api地址都得从一大堆页面里寻找到那小小的一个axios.get,简直深恶痛绝
请封装吧,万物皆能封装,封装治好了你多年的眼疾
封装更合理的Axios操作类
1.导入axios至你的项目
npm install --save axios
2.在根路径创建http.js
首先导入axios至http文件
import axios from 'axios'
配置axios的默认URL
axios.defauls.baseURL = 'xxx'
配置允许跨域携带cookie
axios.defaults.withCredentials = true
配置超时时间
axios.defaults.timeout = 100000
标识这是一个 ajax 请求
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'
配置请求拦截
axios.interceptors.request.use(config => { config.setHeaders([ ... // 在这里设置请求头与携带token信息 ]) return config })
配置相应拦截
// axios拦截器 axios.interceptors.response.use(response => { // 在这里你可以判断后台返回数据携带的请求码 if (response.data.retcode === 200 || response.data.retcode === '200') { return response.data.data || response.data }else { // 非200请求抱错 throw Error(response.data.msg || '服务异常') }
最后返回(更多配置可以查看axio的官方api)
export defaul axios
全部文件
import axios from 'axios' axios.defauls.baseURL = 'xxx' axios.defaults.withCredentials = true axios.defaults.timeout = 100000 // // axios拦截器 axios.interceptors.request.use(config => { config.setHeaders([ ... // 在这里设置请求头与携带token信息 ]) return config }) axios.interceptors.response.use(response => { // 在这里你可以判断后台返回数据携带的请求码 if (response.data.retcode === 200 || response.data.retcode === '200') { return response.data.data || response.data }else { // 非200请求抱错 throw Error(response.data.msg || '服务异常') } export default axios
是不是看到这里大失所望,别着急,接下来再新建一个api.js文件
封装一个匿名函数返回一个apis对象,通过apis对象的键名去获取对应的api地址
// 集中管理路由,所有的接口地址: // 1.整个应用用到了哪些接口一目了然 // 2.接口地址可能变化,方便管理 const prefix = '' // api地址前缀 export default(config => { return Object.keys(config).reduce((copy, name) => { copy[name] = `${prefix}$config[name]` return copy }) })({ // example api "getExampleData": "/api/example/data" })
文件最终返回一个对象
// api对象 { getExampleData: '/api/example/data' }
看到这里是不是有点迷糊,接下来上重头戏~
再新建一个service文件夹,在其下新建一个index.js
(src/server/index.js)
import http from '../http.js' // 导入我们封装好的axios对象 import apis from '../api.js' // 导入我们封装好的apis对象 export funciton getExampleData (params = {}) { // 从外部接受参数,没有参数默认为空对象 retun http.get(apis.getExampleData, params) // return对应的get/post方法,第一个填路径,第二个给参数对象 }
看到这里是不是就恍然大悟了,把获取exampleData这个接口封装成了一个方法,在所需的页面调用对应的方法就好了
Vue页面引用
import { getExampleData } from 'services' ... beforeCreate() { getExampleData({ name: 'xxx'} ).then(res => { this.exampleData = res // 绑定到data里 consonle.log(res) // 这里返回的是你根据http.js拦截器中定义的返回数据 }).catch(err => console.log(err)) // 处理报错信息 } ...
React页面引用
import { getExampleData } from 'services' ... componentWillMount() { getExampleData({ name: 'xxx'} ).then(res => { this.setState({ exampleData: res // 赋值到state里 }) consonle.log(res) // 这里返回的是你根据http.js拦截器中定义的返回数据 }).catch(err => console.log(err)) // 处理报错信息 }
希望大家能用上这个以后不再烦恼apis的杂多或者难以管理,难以修改之类的通病
喜欢就点个赞吧。谢谢你~
转载:https://blog.csdn.net/frank_come/article/details/80010611