react\vue 等框架使用axios,自定义封装requset异步请求

前端不管用那种框架,其中异步请求都可以使用axios插件进行封装,于此整理通用方法。并赋使用方法,

1、以vue为例封装,react同理 此处封装的文件为 globle.vue

import axios from 'axios'
import Vue from 'vue'
import store from '@/store/index' // 自定义vuex store
// 后台接口地址const baseUrl = 'http://dev.xxx.cnpc.com.cn:8080/' // url 地址
const request = axios.create({ //
  baseURL: baseUrl,
  headers: { 'Content-Type': 'application/json;' },
  data: {},
  timeout: 30000,
  changeOrigin: true, // 允许跨域
  credentials: 'include',
  withCredentials: true
})
// http request 请求拦截器
request.interceptors.request.use(
  config => {
    // 增加判断,除登陆接口外,添加token; 此处判断需根据自身项目实际情况进行自定义
    if (config.url.indexOf('account/login') !== 0) {
      config.headers['HRSHTOKEN'] = sessionStorage.getItem('token')
    }
    // config.data = `${JSON.stringify(config.data)}`
    return config
  },
  err => {
    console.log('加载超时')
    return Promise.reject(err)
  })
// http response 返回拦截器
request.interceptors.response.use(
  response => {
// 此处判断依旧根据项目自身情况进行自定义; 此处判断返回status状态为200时表示成功,else进行弹框提示message if (response.data.status === '200') { return response } else { Vue.$vux.toast.show({ text: response.data.message, type: 'text', width: '50%' }) return Promise.reject(new Error(response.data.message)) // 拦截打印错误信息,在调用时,必须加入catch,浏览器才不会显示红色报错 } }, error => { // 请求失败时的提示 console.log(error.response.status) return Promise.reject(error) })

export default {

request

}

2、vue项目的 main.js 进行全局注册,方便调取使用

import _global from '@/global/global'

// 全局注册组件
Vue.prototype.GLOBAL = _global

3、模块文件直接调用, 在模块中进行response 数据处理

 const _this = this
 this.GLOBAL.request.post('tax/taxInfo', reqData).then(({data}) => {
    _this.list = data.payload.list
  }).catch(e => { // 这里必须加入catch不然控制台 error message 显示为红色错误提示
    console.log(e)
  })