菜单

详解vue axios三回封装

2019年5月25日 - Bootstrap

第1步还是先下载axios

这段时日告知项目需求,用到了vue。

cnpm install axios -S

刚发轫搭框架的时候用的是vue-resource前面看到官方推荐axios就换过来了
顺便封装了须臾间

其次步创设3个htttp.js

概念公共参数与引进组件:

import axios from 'axios';
import { Message } from 'element-ui';

axios.defaults.timeout = 5000;
axios.defaults.baseURL ='';


//http request 拦截器
axios.interceptors.request.use(
 config => {
  // const token = getCookie('名称');注意使用的时候需要引入cookie方法,推荐js-cookie
  config.data = JSON.stringify(config.data);
  config.headers = {
   'Content-Type':'application/x-www-form-urlencoded'
  }
  // if(token){
  //  config.params = {'token':token}
  // }
  return config;
 },
 error => {
  return Promise.reject(err);
 }
);


//http response 拦截器
axios.interceptors.response.use(
 response => {
  if(response.data.errCode ==2){
   router.push({
    path:"/login",
    querry:{redirect:router.currentRoute.fullPath}//从哪个页面跳转
   })
  }
  return response;
 },
 error => {
  return Promise.reject(error)
 }
)


/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */

export function fetch(url,params={}){
 return new Promise((resolve,reject) => {
  axios.get(url,{
   params:params
  })
  .then(response => {
   resolve(response.data);
  })
  .catch(err => {
   reject(err)
  })
 })
}


/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */

 export function post(url,data = {}){
  return new Promise((resolve,reject) => {
   axios.post(url,data)
     .then(response => {
      resolve(response.data);
     },err => {
      reject(err)
     })
  })
 }

 /**
 * 封装patch请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function patch(url,data = {}){
 return new Promise((resolve,reject) => {
  axios.patch(url,data)
     .then(response => {
      resolve(response.data);
     },err => {
      reject(err)
     })
 })
}

 /**
 * 封装put请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function put(url,data = {}){
 return new Promise((resolve,reject) => {
  axios.put(url,data)
     .then(response => {
      resolve(response.data);
     },err => {
      reject(err)
     })
 })
}
import axios from 'axios'
import qs from 'qs'

axios.interceptors.request.use(config => {
  //显示loading
 return config
}, error => {
 return Promise.reject(error)
})


axios.interceptors.response.use(response => {
 return response
}, error => {
 return Promise.resolve(error.response)
})

function errorState(response) {
  //隐藏loading
 console.log(response)
 // 如果http状态码正常,则直接返回数据
 if (response && (response.status === 200 || response.status === 304 || response.status === 400)) {
  return response
   // 如果不需要除了data之外的数据,可以直接 return response.data
 }else{
  Vue.prototype.$msg.alert.show({
      title: '提示',
      content: '网络异常'
  })
 }

}

function successState(res) {
  //隐藏loading
 //统一判断后端返回的错误码
 if(res.data.errCode == '000002'){
    Vue.prototype.$msg.alert.show({
      title: '提示',
      content: res.data.errDesc||'网络异常',
      onShow () {
      },
      onHide () {
       console.log('确定')
      }
    })
 }else if(res.data.errCode != '000002'&&res.data.errCode != '000000') {
   Vue.prototype.$msg.alert.show({
      title: '提示',
      content: res.data.errDesc||'网络异常',
      onShow () {

      },
      onHide () {
       console.log('确定')
      }
    })
 }
}
const httpServer = (opts, data) => {

  let Public = { //公共参数
   'srAppid': ""
  }

  let httpDefaultOpts = { //http默认配置
     method:opts.method,
     baseURL,
     url: opts.url,
     timeout: 10000,
     params:Object.assign(Public, data),
     data:qs.stringify(Object.assign(Public, data)),
     headers: opts.method=='get'?{
      'X-Requested-With': 'XMLHttpRequest',
      "Accept": "application/json",
      "Content-Type": "application/json; charset=UTF-8"
     }:{
      'X-Requested-With': 'XMLHttpRequest',
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
     }
  }

  if(opts.method=='get'){
   delete httpDefaultOpts.data
  }else{
   delete httpDefaultOpts.params
  }

  let promise = new Promise(function(resolve, reject) {
   axios(httpDefaultOpts).then(
    (res) => {
     successState(res)
     resolve(res)
    }
   ).catch(
    (response) => {
     errorState(response)
     reject(response)
    }
   )

  })
 return promise
}

export default httpServer

第三步

装进理由:

在main.js中引入

1、能够和后端钻探好错误码在那统1提醒统一管理,省去不必要的分神

import axios from 'axios'
import {post,fetch,patch,put} from './utils/http'
//定义全局变量
Vue.prototype.$post=post;
Vue.prototype.$fetch=fetch;
Vue.prototype.$patch=patch;
Vue.prototype.$put=put;

二、倘若做接口全报文加解密都能够在此管理

终极在组件里平昔动用

接口统1归类:

mounted(){
  this.$fetch('/api/v2/movie/top250')
   .then((response) => {
    console.log(response)
   })
 },

其余的方法一样
const serviceModule = {
 getLocation: {
  url: ' service/location/transfor',
  method: 'get'
 }
}
const ApiSetting = {...serviceModule }

export default ApiSetting

您或然感兴趣的小说:

分拣好处:

一、中期接口晋级恐怕接口名转移便于维护

http调用:

<script>
import http from "../../lib/http.js";
import ApiSetting from "../../lib/ApiSetting.js";
export default {
 created: function() {
  http(ApiSetting.getLocation,{"srChannel": "h5",})
  .then((res)=>{
   console.log(res)
  },(error)=>{
   console.log(error) 
  })
  },
 methods: {

 }
}
</script>

你可能感兴趣的篇章:

相关文章

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图