Reputation: 785
I am not able to access cross domain resources from my javascript file using XMLHttpRequest(). I understand that there are a few similar questions, I went through some of them but I have a bit of confusion regarding some of the details. I will mention my exact Setup and my specific doubts.
Setup:
I have my HTML and JS files on an apache server running on a ubuntu machine present in my local LAN network . The application is bascially hls plugin for video.js. From my windows PC in the same local LAN, I open the index.html file for the hls player. As long as I select video content which is present on the linux machine, it works fine as expected, but on giving it an external content( E.g. http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8), it fails and gives the error:
XMLHttpRequest cannot load http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://172.20.33.49' is therefore not allowed access.
(Here 172.20.33.49 is the IP of the linux machine)
So my queries are:
On which server should the Access-Control-Allow-Origin header be set to appropriate value(lets say '*' for simplicity) for this to work: on my local linux server or the server hosting the external content or both?
Is there any setting/configuration/code change which I need to do in my browser/javascript or HTML code for this to work?
Upvotes: 1
Views: 2584
Reputation: 943571
On which server should the Access-Control-Allow-Origin header be set
The server hosting the content you want to read with XHR. The error message does spell this out, it tells you the URL to a resource that you are requesting and then says that the header is not present on that resource.
Is there any setting/configuration/code change which I need to do in my browser/javascript or HTML code for this to work?
No. The browser handles CORS transparently.
As a general query, is there anything the client can/should do for CORS to work or is it purely a server requirement/configuration?
The client has to support CORS. All modern browsers do.
Is the 'Access-Control-Allow-Origin' mandatory in HTTP responses?
No
If not then what does its absence mean - Does it mean only resources from same domain can be accessed or does it mean all domains are accessible(equivalent to *) ?
If a server doesn't specify Access-Control-Allow-Origin then it doesn't grant permission to any other origin to read its data.
Is there any way a client can force a server to add this header?
No (although a browser extension can intercept the response and add the header, this can be useful for testing purposes).
Upvotes: 2