vue项目自动获取本机局域网ip地址

2020-05-26 15:24:07 浏览数 (1)

config -->index.js中添加

代码语言:javascript复制
const os = require('os');
function getNetworkIp() {
    let needHost = ''; // 打开的host
    try {
        // 获得网络接口列表
        let network = os.networkInterfaces();
        for (let dev in network) {
            let iface = network[dev];
            for (let i = 0; i < iface.length; i  ) {
                let alias = iface[i];
                if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
                    needHost = alias.address;
                }
            }
        }
    } catch (e) {
        needHost = 'localhost';
    }
    return needHost;
}

config -->index.js使用

代码语言:javascript复制
    host: getNetworkIp(),
    port: 8080, 

0 人点赞