美文网首页
vue axios封装(带有token)

vue axios封装(带有token)

作者: 大号火龙果 | 来源:发表于2019-11-25 14:25 被阅读0次

    使用方法:

    在main.js中

    import { get , post } from 'http.js'//当然还是要写好你自己的路径的
    
    /**axios封装
     * 请求拦截、
     */
    import axios from 'axios';
    import router from '../router/index';
    import store from '../store/index.js';
    import { Toast } from 'vant';
    import QS from 'qs';
    
    //配置默认地址
    axios.defaults.baseURL = "你的服务器地址";
    /** 
     * 跳转登录页
     * 携带当前页面路由,以期在登录页面完成登录后返回当前页面
     */
    // const toLogin = () => {
    //     router.replace({
    //         path: '/login',        
    //         query: {
    //             redirect: router.currentRoute.fullPath
    //         }
    //     });
    // }
    //post请求的请求头
    axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
    //axios拦截器,目的是为了在请求头上带上token
    axios.interceptors.request.use(
        config => {
        if (localStorage.getItem('Authorization')) {
          //token字段是要和后端协商好的
            config.headers.common["token"] = localStorage.getItem('Authorization');
            // debugger
        }
        return config;
        },
        error => {
        return Promise.reject(error);
        });
    /**  get方法,对应get请求 
     * @param {String} url [请求的url地址] 
     * @param {Object} params [请求时携带的参数] 
     */
    export function get(url, params){    
        return new Promise((resolve, reject) =>{        
            axios.get(url, {            
                params: params        
            })        
            .then(res => {            
                resolve(res.data);        
            })        
            .catch(err => {            
                reject(err.data)        
            })    
        });
    }
    /** 
     * post方法,对应post请求 
     * @param {String} url [请求的url地址] 
     * @param {Object} params [请求时携带的参数] 
     */
    export function post(url, params) {    
        return new Promise((resolve, reject) => {         
            axios.post(url, QS.stringify(params))        
            .then(res => {            
                resolve(res.data);        
            })        
            .catch(err => {            
                reject(err.data)        
            })    
        });
    }
    
    
    
    

    相关文章

      网友评论

          本文标题:vue axios封装(带有token)

          本文链接:https://www.haomeiwen.com/subject/pdzdwctx.html