2020-05-26 axios封装请求,封装公共api和调用请求

文件目录

├─src                    //应用目录
│  ├─utils               //axios模块
│  │   ├─request.js      //axios实例
│  │   ├─http.js         //封装请求
│  │   ├─state.js        //封装请求
│  ├─api                 //axios模块
│  │   ├─api.js      //axios实例


request.js

import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '../store'

//1. 创建新的axios实例,
const service = axios.create({
  // 公共接口--这里注意后面会讲
  baseURL: process.env.BASE_API,
  // 超时时间 单位是ms,这里设置了3s的超时时间
  timeout: 3 * 1000
})

// 2.请求拦截器
service.interceptors.request.use(

//请求头加token
/*  config => {
    if (localStorage.getItem('Authorization')) {
          config.headers.Authorization = localStorage.getItem('Authorization');
        }
    return config
  }, */
  config => {
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// 3、response 响应拦截器
service.interceptors.response.use(
  response => {
    /**
     * code为非20000是抛错 可结合自己业务进行修改
     */
    const res = response.data
    const codeReg = /^20\d+/
    if (!codeReg.test(response.status)) {
      Message({
        message: res.message,
        type: 'error',
        duration: 5 * 1000
      })

      // 50008:非法的token; 50012:其他客户端登录了;  50014:Token 过期了;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        MessageBox.confirm(
          '你已被登出,可以取消继续留在该页面,或者重新登录',
          '确定登出',
          {
            confirmButtonText: '重新登录',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          store.dispatch('FedLogOut').then(() => {
            location.reload() // 为了重新实例化vue-router对象 避免bug
          })
        })
      }
      return Promise.reject('error')
    } else {
      return response.data
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service

state.js

export const throwErr = (code, response) => {
  let message = '请求错误'
  switch (code) {
    case 400:
      message = '请求错误'
      break
    case 401:
      message = '未授权,请登录'
      break
    case 403:
      message = '拒绝访问'
      break
    case 404:
      message = `请求地址出错: ${response.config.url}`
      break
    case 405:
      message = '请求方法未允许'
      break;  
    case 408:
      message = '请求超时'
      break
    case 500:
      message = '服务器内部错误'
      break
    case 501:
      message = '服务未实现'
      break
    case 502:
      message = '网关错误'
      break
    case 503:
      message = '服务不可用'
      break
    case 504:
      message = '网关超时'
      break
    case 505:
      message = 'HTTP版本不受支持'
      break
    default:
      message = `连接错误${response.status}`
  }
  return message
}

http.js

/****   http.js   ****/
// 导入封装好的axios实例
/****   http.js   ****/
// 导入封装好的axios实例
import request from './request'
//数据处理


const http = {
  /**
   * methods: 请求
   * @param url 请求地址
   * @param params 请求参数
   */
  get(url, params) {
    const config = {
      method: 'get',
      url: url
    }
    if (params) config.params = params
    return request(config)
  },
  post(url, params) {
    const config = {
      method: 'post',
      url: url,
    }
    if (params) config.data = params;
    return request(config)
  },
  put(url, params) {
    const config = {
      method: 'put',
      url: url
    }
    if (params) config.params = params
    return request(config)
  },
  delete(url, params) {
    const config = {
      method: 'delete',
      url: url
    }
    if (params) config.params = params
    return request(config)
  }
}
//导出
export default http

api.js

import http from '../utils/http'
// 
/**
 *  @parms resquest 请求地址 例如:http://197.82.15.15:8088/request/...
 *  @param '/testIp'代表vue-cil中config,index.js中配置的代理
 */
let resquest = "/api/resquest/api/"  //第一个api 是vue.config.js 的跨域路径 后面是线上api接口路径 

// get请求
export function getListAPI(params){
    return http.get(`${resquest}index.php`,{user:'admin',pwd:'123'})
}

// post请求
export function postFormAPI(params){
    return http.post(`${resquest}/index.php`,params)
}

// put 请求
export function putSomeAPI(params){
    return http.put(`${resquest}/index.php`,params)
}

// delete 请求
export function deleteListAPI(params){
    return http.delete(`${resquest}/index.php`,params)
}

页面写法

 getList() {
        api.getListAPI(data).then(res => {
          //数据处理
        }).catch(err => console.log(err))
  }

http 请求 http.js
第一种写法

/****   http.js   ****/
// 导入封装好的axios实例
import request from './request'
//数据处理


const http = {
  /**
   * methods: 请求
   * @param url 请求地址
   * @param params 请求参数
   */
  get(url, params) {
    const config = {
      method: 'get',
      url: url
    }
    if (params) config.params = params
    return request(config)
  },
  post(url, params) {
    const config = {
      method: 'post',
      url: url,
    }
    if (params) config.data = params;
    return request(config)
  },
  put(url, params) {
    const config = {
      method: 'put',
      url: url
    }
    if (params) config.params = params
    return request(config)
  },
  delete(url, params) {
    const config = {
      method: 'delete',
      url: url
    }
    if (params) config.params = params
    return request(config)
  }
}
//导出
export default http

写法2


function apiAxios(method, url, params, response) {
  http({
    method: method,
    url: url,
    data: method === 'POST' || method === 'PUT' ? params : null,
    params: method === 'GET' || method === 'DELETE' ? params : null,
  }).then(function (res) {
    response(res);
  }).catch(function (err) {
    response(err);
  })
}

export default {
  get: function (url, params, response) {
    return apiAxios('GET', url, params, response)
  },
  post: function (url, params, response) {
    return apiAxios('POST', url, params, response)
  },
  put: function (url, params, response) {
    return apiAxios('PUT', url, params, response)
  },
  delete: function (url, params, response) {
    return apiAxios('DELETE', url, params, response)
  }
}

你可能感兴趣的:(2020-05-26 axios封装请求,封装公共api和调用请求)