如何从另一台设备测试使用 Angular CLI 服务创建的应用程序?

How to test an app created with Angular CLI ng serve from another device?

我有一个使用 Angular CLI 从头开始​​生成的应用程序。 CLI 版本 angular-cli: 1.0.0-beta.11-webpack.2

我正在尝试通过我的智能手机对其进行测试,但我收到 连接被拒绝

所以,我 运行 ng serve 在我的笔记本电脑上尝试访问该应用程序:

这用于以前的 SystemJS 版本的 CLI。我检查过我没有安装防火墙 运行ning。

如何修复或调试此错误?

我正在使用 Mac。

添加值为“0.0.0.0”的主机标志应该允许您从本地网络上的任何设备访问网络服务器。

这应该有效: ng serve --host 0.0.0.0

求解释: https://github.com/angular/angular-cli/pull/1475#issuecomment-235986121

你必须在 node_modules angular cli 文件夹中找到所有出现的 localhost 并将(特别是一个,取决于你的 angular-cli 版本)替换为 0.0.0.0 .

然后在 package.json 中输入 ng serve --host 0.0.0.0

在我的例子中,文件是 commands/serve.js

在package.json

 "start": "ng serve --host 0.0.0.0   --port 4200 --disable-host-check ",

但是 --disable-host-check 会存在安全风险 你将需要 "@angular/cli": "^1.1.0-rc.2" 因为这个标志出现在 1.1 版本中

遵循此页面上的建议: https://medium.com/webpack/webpack-dev-server-middleware-security-issues-1489d950874a,这对我有用:

ng serve --host 0.0.0.0 --host my-computer

也许这会有所帮助(@Captain Whippet 的回答有点自动化):

开发-server.js:

const os = require('os');
const { spawn } = require('child_process');

function getLocalIp(ipMatchArr) {
  const networkInterfaces = os.networkInterfaces();
  let matchingIps = Object.keys(networkInterfaces).reduce((arr, name) => {
    const matchingInterface = networkInterfaces[name].find(iface =>
      iface.family === 'IPv4' && ipMatchArr.find(match => iface.address.indexOf(match) > -1));
      if (matchingInterface) arr.push(matchingInterface.address);
      return arr;
  }, []);

  if (matchingIps.length) {
    return matchingIps[0];
  }
  else {
    throw(`Error. Unable to find ip to use as public host: ipMatches=['${ipMatchArr.join("', '")}']`);
  }
}

function launchDevServer(address) {
  const port = process.env.port || 4200;
  const publicHostname = address + ":" + port;
  console.log(`[[[ Access your NG LIVE DEV server on \x1b[33m ${publicHostname} \x1b[0m ]]]`);
  spawn(
      "ng serve"
    , [
          "--host 0.0.0.0"
        , `--public ${publicHostname}`
      ]
    , { stdio: 'inherit', shell: true }
  );
}

/* execute */
launchDevServer(getLocalIp(['192.168.1.', '192.168.0.']));

package.json:

"scripts": {
    "start": "node dev-server.js"
  }

然后 运行 "npm start"

然后,您可以通过以黄色打印的地址在本地网络上的任何设备上打开您的应用程序。

@angular/cli:1.3.2,节点:6.9.5

在 Mac 和 Windows

上测试