axios的常用封装

1.先写一个类

/**
 * axios请求的类
 */

import axios from 'axios'
import {
      MessageBox, Message } from 'element-ui'
import store from '@/store'
import {
      getToken } from '@/utils/auth'
import Env from '@/api/env/index';      
// create an axios instance
const service = axios.create({
     
  baseURL: Env.baseURL,
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 15 * 1000, // request timeout
  withCredentials: false, // 允许携带cookie
  dataType:'JSON',
  headers: {
     
    "Content-Type": "application/json;charset=UTF-8"
  },
})

// request interceptor
service.interceptors.request.use(
  config => {
     
    // do something before request is sent

    if (store.getters.token) {
     
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['X-Token'] = getToken()
    }
    return config
  },
  error => {
     
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
     
    const res = response.data    // if the custom code is not 0, it is judged as an error.
    //状态码200为成功
    if (res.code !== 200) {
     
      Message({
     
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })



 
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
     
      return res
    }
  },
  error => {
     
    console.log('err' + error) // for debug
    Message({
     
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service

2.分类各个页面的接口方法,灵活的选用传输方式

import request from '@/utils/request'   //引入的是上面的那个类

export function getList(params) {
     
  return request({
     
    url: '/vue-admin-template/table/list',
    method: 'get',
    params
  })
}

注:@/api/env/index 上面用到的,用做切换域名

export default {
     
    // 接口地址
    baseURL: 'https://***.com/WA', 
    // baseURL:'http://*****11.2:8080/WA', 
   }

你可能感兴趣的:(js,vue.js,javascript)