vue获取动态地址IP,同时打包可以设置自己想要的端口。

664 阅读1分钟
在封装axios时,默认为IP地址
import axios from 'axios'
const request = axios.create({
    baseURL:`http://${location.hostname}:8080/***`,  // 默认获取本机IP地址
    timeout: 5000,
    headers: {
        // 设置后端需要的传参类型
        "Content-Type": "application/x-www-form-urlencoded",
      },
})

vue-cli3+示例,如何打包后可以获取端口信息

1.添加一个***.js文件
var IPConfig = window.IPConfig = {
    'IP': `http://${location.hostname}`,
    'HOST': '80'
  }
2.然后在封装的axios时把baseURL改写成 baseURL: IPConfig.IP + ':' + IPConfig.HOST + '***',
const request = axios.create({
    baseURL:IPConfig.IP + ':' + IPConfig.HOST + '/***',  // 默认获取本机IP地址
    timeout: 5000,
    headers: {
        // 设置后端需要的传参类型
        "Content-Type": "application/x-www-form-urlencoded",
      },
})
3.再然后在public文件下的index.html引入
 <script type="text/javascript" src="/***/assets/js/IPConfig.js" async></script>

1660295230722.png

4.在打包时,放入打包后的js文件夹,并改写文件路径

1660295360412.png

5.打包部署到服务器时,只需改js文件里的IP端口号即可。
'HOST': '80'      /*你的服务器端口*/