I have an app generated with Angular CLI from scratch. CLI version angular-cli: 1.0.0-beta.11-webpack.2
I am trying to test it from my smartphone but I get
Adding the host-flag with value "0.0.0.0" should allow you to access the webserver from any device on your local network.
This should work:
ng serve --host 0.0.0.0
For an explanation: https://github.com/angular/angular-cli/pull/1475#issuecomment-235986121
you have to find in node_modules angular cli folder all the occurences of localhost and replace (one in particular, depending of your angular-cli version) with 0.0.0.0.
then in package.json put ng serve --host 0.0.0.0
In my case the file is commands/serve.js
In package.json
"start": "ng serve --host 0.0.0.0 --port 4200 --disable-host-check ",
However --disable-host-check
would be a security risk
and you will need
"@angular/cli": "^1.1.0-rc.2"
as this flag appeared in 1.1 version
Maybe this can be helpfull (a bit automated version of @Captain Whippet's answer):
dev-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"
}
You can then open your app on any device on your local network via address printed in yellow.
@angular/cli: 1.3.2, node: 6.9.5
tested on Mac and Windows
Following the advice on this page: https://medium.com/webpack/webpack-dev-server-middleware-security-issues-1489d950874a, this worked for me:
ng serve --host 0.0.0.0 --host my-computer