在做项目的时候遇到了一个问题, 就是把项目部署到不同的服务器上, 但不能每次修改IP的时候就打包一次, 这就增加了前端的工作量,经过百度, 发现有一些方法是可以的,亲测可用。
具体操作是,
1,在static文件夹下面建立一个config.js文件,
1
2
3
4
5
6
7
|
( function () { window.SITE_CONFIG = {} // api接口请求地址 这里写你后端要请求的接口地址,如果只是一个地址,可删除下面的那个 window.SITE_CONFIG[ 'baseUrl' ] = '请求的地址' window.SITE_CONFIG[ 'baseUrl_two' ] = '请求的地址' })() |
2, 在vue项目中的index.html页面引用这个config.js。利用window的属性把地址在全局中暴露出来,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<!DOCTYPE html> <html> <head> <meta charset= "utf-8" > <meta name= "viewport" content= "width=device-width,initial-scale=1.0" > <link rel= "stylesheet" href= "./src/assets/style/index.css" > <title>修改IP</title> <script src= "./static/config.js" ></script> </head> <body> <div id= "app" ></div> <!-- built files will be auto injected --> </body> </html> |
3, 在你封装的请求页面,把这个全局暴露出来的Window属性接口IP写到公共方法里面。
1
2
3
4
5
6
7
8
9
10
11
12
|
import axios from './http' import axiosTwo from './axiosTwo' import store from '../store' let baseUrl=window.SITE_CONFIG.baseUrl //该方法为普通接口调用 请求头不一样 该请求头为 application/json function requestPost([dataList, methodInfo] = [{}, {}]) { return axios.post(`${baseUrl}`, { dataList, methodInfo, }); } |
这样就完成了,重新打包之后,在static文件夹中会生成config.js的文件, 修改这个文件的地址,就可以更换IP地址了。