axios封装
[编程语言教程]

封装axios.js

import axios from ‘axios‘

axios.defaults.widthCredentials = true;
axios.defaults.crossDomain = true;
axios.defaults.timeout = 1000;
axios.defaults.baseURL =‘url‘;
axios.defaults.headers.post[‘Content-Type‘] = ‘applicantion/json;charset=UTF-8‘;
axios.defaults.headers.get[‘Content-Type‘] = ‘application/json;charset=UTF-8‘;
axios.defaults.headers.common[‘Authorization‘] = ‘‘+Cookies.get(tokenKey); // 设置请求头为 Authorization
//加载动画显示
//创建axios实例
let util = {};
util.ajax = axios.create({});
//request 拦截器
util.ajax.interceptors.request.use( config =>{
    return config;
},error => {
    return Promise.reject(error);
})
// response 拦截器
util.ajax.interceptors.response.use( response =>{
    if(laoding){
        loading.close();
    }
    if(response.data.code === ‘401‘){
        console.log(‘response----------‘, response);
        //全局登陆过滤,当判读token失效或者没有登录时 返回登陆页面
        return false;
    }
    return Promise.resolve(response);
}, error =>{
    loading.close();
    return Promise.reject(error)
})
export default {
    /*
   * get方法,对应get请求
   * @param {String} url [请求的url地址]
   * @param {Object} params [请求时携带的参数]
   */
   get (url, params) {
       return new Promise( (resolve, reject) =>{
           util.ajax.get(url, {params: params},
           {
                headers: {
                    ‘Authorization‘: ‘‘ + getToken(‘Token‘),
                    ‘token‘: getToken(‘Token‘)
                }
           }).then(res => {
               resolve(res)
           }).catch(err => {
               reject(err)
           })
       })
   },
    /**
   * post方法,对应post请求
   * @param {String} url [请求的url地址]
   * @param {Object} params [请求时携带的参数]
   */
   post (url, params) {
    return new Promise((resolve, reject) => {
      util.ajax.post(url, params,
        {
          headers: {
            ‘Authorization‘: ‘‘ + getToken(‘Token‘),
          }
        })
        .then(res => {
          resolve(res.data)
        })
        .catch(err => {
          reject(err)
        })
    })
  }
}
hmoban主题是根据ripro二开的主题,极致后台体验,无插件,集成会员系统
自学咖网 » axios封装