前言

假如你的Vue项目需要在多个服务器部署,若使用代理的模式,每个环境都需要先改IP地址及端口,再打包,非常的麻烦,所以本文没有用代理,而是通过Ajax同步获取配置文件信息,封装一个axios请求


一、建立public目录及配置文件

在主目录(即和src同目录)创建public文件夹,创建config.json文件
在这里插入图片描述
config.json文件实例:
{
“url”: “http://localhost:8090”,
“webSocket”: “ws://localhost:8090//webSocket/”
}

二、封装axios请求及引入

1.封装axios请求 api->index.js

在这里插入图片描述
api->index.js代码如下:

import axios from 'axios'
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
let baseURL;
let webSocket;

const getBaseUrl = function () {
    $.ajax({
        type : "get",
        async: false, // fasle表示同步请求,true表示异步请求
        url : "./config.json",
        data : {},
        success : function(result) {
            baseURL = result.url;
            webSocket = result.webSocket;
        },
        error : function(e){
            console.log(e);
        }
    });
};

//动态获取ip
getBaseUrl();

const instance = axios.create({
    baseURL: baseURL
})

//全局请求拦截
instance.interceptors.request.use(function(request) {
    return request;
}, function(error) {
    return Promise.reject(error);
})

//全局响应拦截
instance.interceptors.response.use(function(response) {
    return response;
}, function(error) {
    return Promise.reject(error);
})


const get = (url, params) => {
    return instance.get(url, params)
}

const post = (url, data) => {
    return instance.post(url, data)
}

// 因为我的项目之前调接口使用的是this.$axios.post()  
// 为了不动之前的代码 所以这里用了$axios 若是新项目,可自定义名称,方便与原版的$axios区分
export default function(Vue) {
    Vue.prototype.$axios = {
        baseURL,
        webSocket,
        get,
        post
    }
}

2.main.js引入上一步封装的index.js

在这里插入图片描述
main.js代码如下(示例):

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import ElementUI from 'element-ui';
Vue.use(ElementUI);
import 'amfe-flexible'
import 'element-ui/lib/theme-chalk/index.css';

// 因为我的项目之前调接口使用的是this.$axios.post()  
// 为了不动之前的代码 所以这里用了$axios 若是新项目,可自定义名称,方便与原版的$axios区分
import $axios from "./api/index.js"
Vue.use($axios)

import qs from 'qs'
Vue.prototype.$qs = qs
import Echart from "echarts";
Vue.prototype.$echarts = Echart;
import moment from "moment";
Vue.prototype.$moment = moment;
Vue.config.productionTip = false;

new Vue({
    router,
    store,
    render: h => h(App)
}).$mount('#app')

3.调用接口代码不变

调用代码示例

methods: {
	getData() {
	      this.$axios.get("/api/getData").then((res) => {
	       //。。。
	     });
	}
}

4.打包后修改配置,改完即时生效

在这里插入图片描述

Logo

前往低代码交流专区

更多推荐