vue中axios设置公共请求地址

场景

vue项目,后台请求地址在配置文件中已经设置为全局的,每次变动只需修改一次即可,然后要部署到三台服务器。

然后:修改服务器地址,打包,部署 --> 修改服务器地址,打包,部署 --> 修改服务器地址,打包,部署 (3次 " for循环 ")

那么当我们需要部署多台服务器的时候,怎么避免减少重复性的工作呢?

下面介绍一种方法来减少任务量:

1、新建配置文件(config.js)

如果是vue2.0的脚手架搭建的项目就在static新建一个配置文件,如果是vue3.0的脚手架搭建的项目,就在public下新建个配置文件,只要保证build后会被打包即可。

文件内容:服务器的ip地址、端口号地址、接口请求地址

window.dasConfig = {
  ip: '1.2.3.4',
  port: 9000,
  dbSourceApi: 'api/DbSourceManage',
  jobMetaApi: 'api/JobMetaManage'
};

2、index.html引用配置文件

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <link rel="Shortcut Icon" href="static/img/logo.ico" type="image/x-icon" />
    <script src="./static/dasConfig.js"></script>   <!-- 引用配置文件 -->
    <title>index</title>
  </head>
  <body>
    <div id="app"></div>
    <!-- built files will be auto injected -->
  </body>
</html>

3、组件中请求接口使用:

init() {
      // 请求后端数据,查询元数据
      this.axios({
        method: 'get',
        url: `http://${window.dasConfig.ip}:${window.dasConfig.port}/${window.dasConfig.jobMetaApi}/GetAllJob`
      })
        .then(response => {
          console.log(response);
        })
        .catch(error => {
          console.log(error);
        });
}

4、打包

之后只需要打包一次,然后打包后的static文件夹中会保留当前配置文件,然后对应服务器进行修改即可。but,可能很多人没有这种需求,只需要打包配置一台服务器即可,可以看下另一篇文章,有详细教程:
vue结合axios实现restful风格的四种请求详解

发布了93 篇原创文章 · 获赞 60 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_43363871/article/details/101675885