VUE local and intranet (remote) access configuration

Since Hyper-V is enabled on the local computer, the internal network obtained by default is the IP of the virtual network card, so a special method is required to obtain the internal network IP

1. package.json

original code

  "scripts": {
    "dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
  },

changed to

  "scripts": {
    "dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js  --host 0.0.0.0",
  },

2. webpack.dev.conf.js

  1. Add code (dynamically obtain local IP)—— Note: Since Hyper-V is enabled on this machine, a special method is required to obtain the intranet IP

// 获取本地ip
function getNetWorkIp() {
  // 打开host
  let needHost = '';
  try {
      let network = os.networkInterfaces();
      for (const dev in network) {
          let iface = network[dev];
          for (let i = 0; i < iface.length; i++) {
              const alias = iface[i];
              if (
                  alias.family === 'IPv4' &&
                  alias.address !== '127.0.0.1' &&
                  !alias.internal
              ) {
                  needHost = alias.address;
              }
          }
      }
  } catch (error) {
      needHost = 'http://localhost';
  }
  return needHost
}
const IP = getNetWorkIp();
  1. Code changes from

      devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({
        compilationSuccessInfo: {
          messages: [`Your application is running here: http://${devWebpackConfig.devServer.host}:${port}`],
        },
        onErrors: config.dev.notifyOnErrors
        ? utils.createNotifierCallback()
        : undefined
      }))

changed to

      devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({
        compilationSuccessInfo: {
          messages: [
            `App runing at: `,
            `本地: http://${devWebpackConfig.devServer.host}:${port}`,
            `内网: http://${IP}:${port}`,
          ],
        },
        onErrors: config.dev.notifyOnErrors
        ? utils.createNotifierCallback()
        : undefined
      }))

Note: There are other methods on the Internet to obtain the IP of the internal website. After trying to open the Hyper-V state of the computer , the desired IP is not obtained, but the IP of the Ethernet adapter vEthernet (Default Switch) is obtained.

  1. require('ip').address()

  1. require('address').ip() has been tested, this method requires a special installation of address( npm i address -D )

The results obtained by the previous two commands are as follows

This IP can be accessed locally, but cannot be accessed by other terminals under the same WIFI

  1. The getNetWorkIp method written above can get the IP I want, and the result is as follows

As shown above, the IPv4 address is the desired result.

Guess you like

Origin blog.csdn.net/qq960685827/article/details/129218592