Two packages for Axios in Vue project

Source: Internet
Author: User

Recently when using the Vue refactoring Company M station, Axios was used to request data, and as a result of the project, the Axios was encapsulated two times, click into Axios

//引入axiosimport axios from ‘axios‘let cancel ,promiseArr = {}const CancelToken = axios.CancelToken;//请求拦截器axios.interceptors.request.use(config => {    //发起请求时,取消掉当前正在进行的相同请求    if (promiseArr[config.url]) {        promiseArr[config.url](‘操作取消‘)        promiseArr[config.url] = cancel    } else {        promiseArr[config.url] = cancel    }      return config}, error => {    return Promise.reject(error)})//响应拦截器即异常处理axios.interceptors.response.use(response => {    return response}, error => {    if (error && err.response) {      switch (err.response.status) {        case 400:          err.message = ‘错误请求‘          break;        case 401:          err.message = ‘未授权,请重新登录‘          break;        case 403:          err.message = ‘拒绝访问‘          break;        case 404:          err.message = ‘请求错误,未找到该资源‘          break;        case 405:          err.message = ‘请求方法未允许‘          break;        case 408:          err.message = ‘请求超时‘          break;        case 500:          err.message = ‘服务器端出错‘          break;        case 501:          err.message = ‘网络未实现‘          break;        case 502:          err.message = ‘网络错误‘          break;        case 503:          err.message = ‘服务不可用‘          break;        case 504:          err.message = ‘网络超时‘          break;        case 505:          err.message = ‘http版本不支持该请求‘          break;        default:          err.message = `连接错误${err.response.status}`      }    } else {      err.message = "连接到服务器失败"    }    message.error(err.message)      return Promise.resolve(error.response)})axios.defaults.baseURL = ‘/api‘//设置默认请求头axios.defaults.headers = {    ‘X-Requested-With‘: ‘XMLHttpRequest‘}axios.defaults.timeout = 10000export default {  //get请求    get (url,param) {      return new Promise((resolve,reject) => {        axios({          method: ‘get‘,          url,          params: param,          cancelToken: new CancelToken(c => {            cancel = c          })        }).then(res => {          resolve(res)        })      })    },  //post请求    post (url,param) {      return new Promise((resolve,reject) => {        axios({          method: ‘post‘,          url,          data: param,          cancelToken: new CancelToken(c => {            cancel = c          })        }).then(res => {          resolve(res)        })      })     }  }
Description

1. In order to prevent the request, the same request is currently in progress, in the request interceptor added hash judgment, the same request URL interception
2. Extract the Get,post public configuration from the Axios

axios.defaults.baseURL = ‘/api‘//设置默认请求头axios.defaults.headers = {    ‘X-Requested-With‘: ‘XMLHttpRequest‘}axios.defaults.timeout = 10000

Encapsulation of 3.get,post Requests

Perhaps you will ask, here Axios return is the Promise object, why again to get,post encapsulation once promise. Because of my side, using async await in development will result in a failure of the data request. The fault of the report is that it is not the Promise object returned. (PS: Can be async await return is promise ah, this problem follow up again to get a bit) return a Promise object directly, to avoid above error. Here is an example of a request interface

import req from ‘../api/requestType‘/** 4. 拼团详情 */export const groupDetail = param => {    returnreq.get(‘/RestHome/GroupDetail‘,param)}

Here's how the data gets

async getData() {    const params = {        TopCataID: 0,        pageNumber: this.pageNumber,        pageSize: this.pageSize    }    const res = await groupList(params)},

1. Global exception handling for common error requests in the appropriate interceptor

axios.interceptors.response.use(response => {...

Here we simply encapsulate the Axios for your project.

Original link: 1190000012332982

Two packages for Axios in Vue project

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.