Reputation: 3691
I get the following error from an ajax request in Firefox:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://www.example.org/php/save.php. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
I tried to find out why this is happening. It is strange since
I also tried
xhttp = new XMLHttpRequest({mozSystem: true});
as suggested here: https://stackoverflow.com/a/22392080
But that did not help either.
I am using the following command to open the request:
xhttp.open('POST', '/php/save.php', true);
I found a number of other solution for when the file is on another server:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
But I don't see why I should do this if the file is actually on the same server...
Edit
I removed the following two lines from my .htaccess
file and now it works.
RewriteCond %{HTTP_HOST} !^www\.example\.org$ [NC]
RewriteRule .? http://www.example.org%{REQUEST_URI} [R=301,L]
Though I am not sure why... maybe the adding of www.
works like moving to a subdomain?
What would I have to add to my .htaccess
file to get it to work with ajax and the rewrite?
Upvotes: 0
Views: 2530
Reputation: 3691
This is what solved my problem - though I am not sure why. Instead of the rewrite I used before I use:
RewriteCond %{HTTP_HOST} !^www\.example\.org$ [NC]
RewriteRule ^(.*)$ http://www.example.org/$1 [R=301,L]
Upvotes: 1
Reputation: 73918
For security reasons, browsers restrict cross-origin HTTP requests initiated from within scripts. For example, XMLHttpRequest and Fetch follow the same-origin policy. So, a web application using XMLHttpRequest or Fetch could only make HTTP requests to its own domain.
To enable your request across different domain you could:
CORS is a standard mechanism that can be used by all browsers for implementing cross-domain requests. You specify a set of headers that allow the browser and server to communicate.
Useful resource: http://enable-cors.org/
Use a reverse proxy.
Use JSONP (works only if you need to read data).
More infos: https://en.wikipedia.org/wiki/Cross-origin_resource_sharing
Upvotes: 0