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