美文网首页
axios 封装、proxyTable代理设置

axios 封装、proxyTable代理设置

作者: 守鶴yuan | 来源:发表于2019-06-06 15:14 被阅读0次
    1. axios 封装
    2. 设置代理
    3. 打包时,设置不同的接口地址
    4. 其他

    1.axios封装

    //HttpService.js
    import axios from 'axios';
    import qs from 'qs';
    import * as common from './common';
    
    let API_HOST = '/dev';
    if (process.env.HOST === 'prod') {
        API_HOST = 'http://prod.com';
    } else if (process.env.HOST === 'test') {
        API_HOST = 'http://test.com';
    }
    // 添加请求拦截器
    axios.interceptors.request.use(function (config) {
        let token = common.$_userx.token();
        // 在发送请求之前做些什么
        if (token) {
            config.headers.login_token = token;
        }
        return config;
    });
    // 添加响应拦截器
    axios.interceptors.response.use(function (response) {
        if (response.data.code !== 200) {
            if(response.data.code === 3005){
                common.$_out();
            }
            return Promise.reject(response.data);
        }
        return response.data;
    });
    
    
    function get(url, data) {
        return axios.get(API_HOST + url, {
            params: data
        });
    }
    
    function post(url, data) {
        let token = common.$_userx.token();
        data['login_token'] = token;
        return axios.post(API_HOST + url, qs.stringify(data));
    }
    
    export default {
        get, post
    }
    
    

    1.1 全局设置

    //main.js
    import axios from './utils/HttpService';
    //全局方法
    Vue.prototype.$http = axios;
    

    1.2调用

    this.$http.post('xxx/xxx', {
      a:1
    }).then(res=>{}).catch(res=>{})
    

    2.设置代理

      //config/index.js
    
     proxyList: {
            '/dev': {
                target: 'http://192.168.0.0:0000',  // 接口的域名
                // secure: false,  // 如果是https接口,需要配置这个参数
                changeOrigin: true, // 如果接口跨域,需要进行这个参数配置
                pathRewrite: {
                    '^/dev': ''
                }
            }
        }
    

    3.打包时,设置不同的接口地址

    //config.js/prod.env.js
    'use strict'
    let HOST = process.argv.splice(2)[0] || 'prod';
    module.exports = {
        NODE_ENV: '"production"',
        HOST: '"'+HOST+'"'
    }
    
    //HttpService.js
    let API_HOST = '/dev';
    if (process.env.HOST === 'prod') {
        API_HOST = 'http://prod.com';
    } else if (process.env.HOST === 'test') {
        API_HOST = 'http://test.com';
    }
    
    //打包命令
    npm run build -- test    --> 测试环境
    npm run build -- prod    --> 正式环境
    

    4.其他

    4.1 Axios使用说明: https://www.kancloud.cn/yunye/axios/234845

    相关文章

      网友评论

          本文标题:axios 封装、proxyTable代理设置

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