iview-admin axios配置及 webpack 代理

25 篇文章 0 订阅
4 篇文章 0 订阅

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用空替换掉
            }
        },
    },

 

4、使用,(有朋友再问怎么使用,就补充一下)

因为方法是扩展的vue原型上的,直接使用this.$ajax即可。

/**
第一个参数:请求接口路径   必须
第二个参数:请求体data   非必须
第三个参数:设置Content-Type  非必须

**/
配合async  await 使用更佳

let result = await this.$ajax.post("url", data
       ,{ "Content-Type": "application/json"});


let result = await this.$ajax.get("url", data
       ,{ "Content-Type": "application/json"});

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值