iview-admin axios配置及 webpack 代理

1、在main.js同级目录下   新建api.js

import axios from 'axios';
import qs from 'qs';

//设置默认请求方式,指定Content-Type
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
const instance = axios.create({
  baseURL: '/api', 
  timeout: 3000,  
});

//vue全局扩展方法接口
function install(Vue) {
  Vue.prototype.$ajax = {
    post,
    get
  };
}

//post请求方法,并根据不同请求类型传入指定的 headers

async function post(url, opts = {}, headers) {
  var result = {};
  try {
    result = await instance.post(url, qs.stringify(opts), headers);
  } catch (e) {
    console.log(e)
    result = e.response || {
      data: null
    };
  }
  return result.data;
}

async function get(url, type, opts = {}) {
  var result = {};

  try {
    result = await instance.get(url, opts);
  } catch (e) {
    console.log(e)
    result = e.response || {
      data: null
    };
  }
  return result.data;
}

export default {
  install
}

2、在 main.js中全局引用即可

//在main.js中添加

import api from "./api";
Vue.use(api);

3、webpack 代理

webpack.base.config.js,在module.exports 中添加

  devServer: {
        historyApiFallback: true,
        hot: true,
        inline: true,
        stats: { colors: true },
        proxy: {
            "/api": {  //axios中给请求添加 /api,用于代理标识
                  target: 'http://1.1.1.1:8081',   //目标地址
                  secure: false, // 接受 运行在 https 上的服务
                  changeOrigin: true,
                  pathRewrite:{'^/api':''}, //重写请求路径,把/api用空替换掉
            }
        },
    },

 

你可能感兴趣的:(javascript,vue,iview-admin)