axios 代理+全局配置

在 项目中安装axios

cnpm install axios -S

 

在 项目中安装http-proxy-middleware中间件作为代理

cnpm install -D http-proxy-middleware

 

http-proxy-middleware这个中间件进行本地代理配置,在项目中找到

config/index.js>module.exports>dev>proxyTable

proxyTable: {
  '/api': {
    target: '',   // 你请求的第三方接口 
    changeOrigin: true,
    secure: false,
    logLevel: 'debug',
    router: {}
  }
},

 

在Src目录新建API文件夹

添加 index axios http 文件夹

 

index.js内容

 

const files = require.context('.', false, /\.js$/);
const modules = {};

files.keys().forEach((key) => {
    if (key === './index.js' || key === './axios.js') return;
    modules[key.replace(/(\.\/|\.js)/g, '')] = files(key).default;
});

export default modules;

axios.js内容

 

import axios from 'axios';

axios.defaults.timeout = 5000;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
axios.defaults.baseURL = (process.env.NODE_ENV === 'production' ? './api/' : '/api/');

// POST传参序列化
axios.interceptors.request.use((config) => {
    if (window.xtoken) {
        config.headers['x-hzdamei'] = window.xtoken;
    }
    if (config.method === 'post') {
        let formdata = new FormData();
        for (let k in config.data) {
            formdata.append(k, config.data[k]);
        }
        config.data = formdata;
    }
    return config;
}, (error) => {
    if (error) {
        console.log('axios.interceptors.request', error);
    }
    const err = {
        data: {
            code: 400,
            msg: '错误的传参!'
        }
    };
    return Promise.reject(err);
});

// code状态码200判断
axios.interceptors.response.use((res) => {
    if (Number(res.data.code) !== 200) {
        return Promise.reject(res);
    }
    return res;
}, (error) => {
    if (error) {
        console.log('axios.interceptors.response', error);
    }
    const err = {
        data: {
            code: 404,
            msg: '网络有点慢,换个姿势再来一次!'
        }
    };
    return Promise.reject(err);
});

export default axios;

http.js内容

 

import axios from './axios';

/**
 * axios实现post
 */
const fetch = (url, options = {}) => {
    let axiosConf = {
        url: url
    };
    if (options.method && options.method.toLowerCase() === 'post') {
        // 如果是POST请求,初始化参数
        axiosConf.method = 'post';
        axiosConf.data = options.body || {};
    } else {
        // 不是POST请求就是GET请求!初始化参数
        axiosConf.method = 'get';
        axiosConf.params = options.body || {};
    }
    return axios(axiosConf)
        .then(res => {
            res.data.success = true;
            return res.data;
        })
        .catch(err => {
            err.data || (err.data = {});
            if (err.data.msg) {
                console.log('fetchError =>', err.data.msg);
            } else {
                console.log('fetchError =>', err);
                err.data.msg = 'SYSTEM ERROR!';
            }
            err.data.success = false;
            return err.data;
        });
};

/**
 * axios实现get
 */
const get = (url, params = {}) => {
    return fetch(url, {
        method: 'get',
        body: params
    });
};

/**
 * axios实现post
 */
const post = (url, data = {}) => {
    return fetch(url, {
        method: 'post',
        body: data
    });
};

export default {
    fetch,
    get,
    post
};

main.js引入axios

 

import api from '@/api';
Vue.prototype.$api = api; // 全局添加$api

添加快捷引入build>webpack.base.conf.js>module.exports>resolve>alias

 

alias: {
  'vue$': 'vue/dist/vue.esm.js',
  '@': resolve('src'),
  '~constant': resolve('src/constant'),        // 常量
  '~scripts': resolve('src/scripts'),          // 脚本
  '~api': resolve('src/api'),                  // api
  '~views': resolve('src/views'),              // 页面
  '~components': resolve('src/components'),    // 组件
  '~assets': resolve('src/assets'),            // 资源
  '~images': resolve('src/assets/images'),     // 资源 => 图片
  '~styles': resolve('src/assets/styles'),     // 资源 => 样式
  '~fonts': resolve('src/assets/fonts'),       // 资源 => 字体
  '~router': resolve('src/router'),            // vue-router
  '~store': resolve('src/store/store.js'),     // vuex
}

api目录内新建任意文件

 

import http from './http'
// 内容管理
export default {
  // 获取文章
  fetchArticle: opts => {             // 接口名称
    const url = 'article/index.html'    // 接口地址
    const data = {            // 参数
      page: opts.page || '',
      page_size: opts.page_size || '',
      is_delete: opts.is_delete || '',
      category: opts.category || '',
      status: opts.status || '',
      title: opts.title || ''
    }
    return http.get(url, data) // 请求方式
  }
}

请求页面

 




 

 

 

你可能感兴趣的:(axios 代理+全局配置)