node获取本机ip地址
1、问题:用node开服务的时候,一般用http://localhost:端口号,本地访问没问题,但是在局域网内使用就需要ip来代替localhost分享给其他小伙伴
2、解决:每次开服务之前:动态获取本机ip,并把ip全局化,保持url统一通用,就做到了打开vue项目的感觉
const os = require('os');
/**
* 获取当前机器的ip地址
*/
function getIpAddress() {
let ifaces = os.networkInterfaces()
for (let dev in ifaces) {
let iface = ifaces[dev]
for (let i = 0; i < iface.length; i++) {
let { family, address, internal } = iface[i]
if (family === 'IPv4' && address !== '127.0.0.1' && !internal) {
return address
}
}
}
}
let ipAddress = getIpAddress()
console.log('http://' + ipAddress + ':3000')
3、效果:


浙公网安备 33010602011771号