Fix "invalid host header" in Angular

Viewed 23356

I have an app in Angular v4 which have to change the scss dependong of the url of access. For example: if link in the browser is "example.com" then the app have background-color: black if the link is"example2.com" then the background-color: red

I have the next problem:

when I go to the hosts in C:\Windows\System32\drivers\etc and I set the next configuration in hosts 127.0.0.1 example.com 127.0.0.1 example2.com

then I run the app with "example.com:4200" the app doesn't run... the browser show me this message

"invalid host header"

How do I fix this problem?

3 Answers

This appeared for me under angular 7.2.1

Assuming you're using the Angular CLI, the solution was to add the following line in angular.json under architect>serve>options:

"disableHostCheck": true

The Reason -

Most development-oriented application servers (such as ng, webpack-dev-server, or WAMPP) default to only binding to localhost (or in some cases blocking traffic directly). Essentially, only traffic directed to your machine from itself is allowed to pass through, meaning that traffic passing through the tunnel will not work the same as traffic coming from your machine directly. Even though it works on your machine, the way the server is set up makes it so that even other local machines cannot connect to it.

How do I fix it?

In most cases, the fix is to tell the server to restart and allow connections from outside localhost.

  1. ng (Angular) => Kill the server and restart it, adding

    --host 0.0.0.0 --disableHostCheck true 
    

    to the command.

  2. Angular2 => Same as above, but add

    --host 0.0.0.0  --disable-host-check
    

    instead

  3. webpack-dev-server => Kill the server and restart it, adding

    --host 0.0.0.0
    

    to the command.

--disable-host-check is sometimes needed here as well.

Related