2

This topic has been discussed in different flavors before, but I have not yet found a solution that works for me. I'm using jquery 1.7.1.

I have a REST style web service that can return both JSON and XML, but for this project I need to use the XML endpoint. To get around the cross domain restrictions, I've created a transparent proxy using Perl's HTTP::Proxy. This proxy works as a breeze since I can talk to it with HTTP GET clients from anywhere.

Since it is a transparent proxy, it relies on the Host header being set in the client request. My code looks like this:

  $.ajax({
    type: "GET",
    crossDomain: true, // not needed I think
    error: function() { alert('Failed ..'); },
    url: "http://www.skiforeningen.no:8080/<remote REST URL>",
    dataType: "xml",
    headers: {'Host': 'remote REST host'},
    success: parseXml,
});

Chrome is very explicit, and says

Refused to set unsafe header "Host"

and

XMLHttpRequest cannot load http://www.skiforeningen.no:8080/sted/Norge/Oslo/Oslo/Skansebakken/varsel.xml. Origin http://www.skiforeningen.no is not allowed by Access-Control-Allow-Origin

but both the proxy and the HTML page with jquery sits on the host www.skiforeningen.no.

FF also refuses to set the Host header (apparently) since the error event handler is triggered.

Thanks,

Didier Ghys
  • 30,396
  • 9
  • 75
  • 81

2 Answers2

5

You cannot do an XHR request on a different host, juste like the error message tells you. A different port means a different host.

See: Can I use XMLHttpRequest on a different port from a script file loaded from that port?

Community
  • 1
  • 1
greut
  • 4,305
  • 1
  • 30
  • 49
0

Certain headers are forbidden and cannot be set programmatically:

  • Accept-Charset
  • Accept-Encoding
  • Access-Control-Request-Headers
  • Access-Control-Request-Method
  • Connection
  • Content-Length
  • Cookie
  • Cookie2
  • Date
  • DNT
  • Expect
  • Feature-Policy
  • Host
  • Keep-Alive
  • Origin
  • Proxy-
  • Sec-
  • Referer
  • TE
  • Trailer
  • Transfer-Encoding
  • Upgrade
  • Via

This is why you cannot set host.

greut's answer regarding not being able to do XHR requests to a different host is incorrect - nothing stops the request being made.

The error simply means that your page in its own origin has no access to the response due to the Same Origin Policy (SOP).

Fiddle here which shows that the HTTP request is actually made when you observe it via a proxy:

HTTP Request

Therefore if you don't care about the response, your method works, although you may want to handle this expected error more gracefully. If you do care about the response you will have to configure CORS on the remote server to let the response be read cross-domain. Set crossDomain to true to prevent any extra headers being added by JQuery that may cause an OPTIONS request to be issued (i.e. X-Requested-With).

SilverlightFox
  • 32,436
  • 11
  • 76
  • 145