vue项目中怎么获取当前用户ip?
一、在项目的config/index.js文件下插入如下代码:
1 const os = require('os'); 2 3 function getNetworkIp() { 4 let needHost = ''; // 打开的host 5 try { 6 // 获得网络接口列表 7 let network = os.networkInterfaces(); 8 // console.log("network",network) 9 for (let dev in network) { 10 11 let iface = network[dev]; 12 for (let i = 0; i < iface.length; i++) { 13 let alias = iface[i]; 14 if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) { 15 needHost = alias.address; 16 // console.log("alias.address",alias.address) 17 } 18 // console.log("alias",alias) 19 } 20 } 21 } catch (e) { 22 needHost = 'localhost'; 23 } 24 return needHost; 25 }
二、在项目的config/index.js文件下修改host:
三、在页面需要的地方获取ip:
var ip = window.location.host; console.log("ip",ip.split(":")[0])
这样就能得到我们需要的ip了。。。