node 獲取本機ip地址
阿新 • • 發佈:2022-12-08
方法一:
node 14之前的
node 14之前的
require('os').networkInterfaces()[Object.keys(require('os').networkInterfaces())[0]][1].address + ':8080'
vue.config.js
module.exports = { lintOnSave: false, // 是否開啟eslint儲存檢測,有效值:ture | false | 'error' publicPath: '', outputDir: process.env.outputDir, devServer: { public: require('os').networkInterfaces()[Object.keys(require('os').networkInterfaces())[0]][1].address + ':8080',disableHostCheck: true, open: true, proxy: { '/api': { target: 'http://xxx.com', pathRewrite: {'^/api' : ''}, changeOrigin: true, secure: false, }, } }, };
方法二:
node 14 之後的
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 } } } }
vue.config.js
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 } } } } module.exports = { lintOnSave: false, // 是否開啟eslint儲存檢測,有效值:ture | false | 'error' publicPath: '', outputDir: process.env.outputDir, devServer: { public: getIpAddress() + ':8080', disableHostCheck: true, open: true, proxy: { '/api': { target: 'http://mh.885505.com', pathRewrite: {'^/api' : ''}, changeOrigin: true, secure: false, }, } }, };
效果:
注: 我之前用的是node 8、 node 12 用的第一種方法,後來升級node 14 執行時報錯了 找不到 address , 方法二可以;