vue本地項目,想要在手機端訪問的時候,需要在vue.config.js的devServe中修改 host的值
host: "localhost" ==> host: "**.**.**.**"
但每次啟動前都要手動查詢ipconfig/ifconfig,比較麻煩。
所以,用nodejs的‘os’來自動獲取本地ip
1 'use strict' 2 const os = require('os') 3 4 /** 5 * 獲取當前機器的ip地址 6 */ 7 function getIpAddress() { 8 var interfaces=os.networkInterfaces() 9 10 for (var dev in interfaces) { 11 let iface = interfaces[dev] 12 13 for (let i = 0; i < iface.length; i++) { 14 let {family, address, internal} = iface[i] 15 16 if (family === 'IPv4' && address !== '127.0.0.1' && !internal) { 17 return address 18 } 19 } 20 } 21 } 22 23 const ipAddress = getIpAddress() 24 console.log(ipAddress) 25 26 module.exports = { 27 ipAddress 28 }