Grégoire Roussel Grégoire Roussel - 24 days ago 8
HTTP Question

Force value of 'Host' header in Angular $http request

I want to access an API site hosted on a multi-site server S. I have the ip adress of S, but there aren't DNS servers, so I have to make a http request with the following parameters :

{
URL : 'http://192.168.1.xxx:80/data',
headers : {
Host : 'api.somesite.com'
},
data : ...
}


However, the 'Host' header is automatically replaced by Angular to '192.168.1.xxx' before sending (and thus the request fails).
I already tried to implement a http interceptor :

api.run(['$http',function($http) {
console.log("set host");
$http.defaults.headers.common.Host = "api.somesite.com";
}]);


...without results : the server answers with an ERROR 500, and Development Tools show that the request had the header 'Host' set to the ip address.

Alternatively, are there other ways to make an http request to a Website by using its ip (without DNS)?

Answer

Host is defined a forbidden header name in the XMLHttpRequest / fetch specifications so it is impossible to set it from JavaScript in the browser.

Sorting out DNS, editing the system hosts file on a per-client basis, or configuring each client to use an HTTP proxy that knows how to resolve the URL are the only ways you can solve this problem.