nodejs获取 本地ip地址


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 }

 

 

 

 

 




					


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM