These three headers are added using PHP
header('Content-Type: application/json; charset=UTF-8;');
header('Access-Control-Allow-Methods: GET, POST');
header('Access-Control-Allow-Origin: *');
All the headers sent are:
HTTP/1.1 200 OK
Date: Mon, 30 Jun 2014 06:39:29 GMT
Server: Apache
X-Powered-By: PHP/5.3.28
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Origin: *
Vary: Accept-Encoding,User-Agent
Content-Encoding: gzip
Cache-Control: max-age=1, private, must-revalidate
Content-Length: 20
Keep-Alive: timeout=3, max=100
Connection: Keep-Alive
Content-Type: application/json; charset=UTF-8;
Yet when trying to use $.json or $.post to target this server, I get this error in the Chrome Console:
XMLHttpRequest cannot load http://cms.webdevguru.co.uk/gurucms.php?mode=addto&apikey=606717496665bcba. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://remote.webdevguru.co.uk' is therefore not allowed access.
I know this is a possible duplicate of a few other questions, but since I have gone through many of them and tried a few things out of them to try and fix this: I would appreciate some specific replies to deal with my issue at hand.
As Joachim Isaksson figured out, its because the initial headers consist of a 301 Redirect, is there any way to force the request to follow the Redirect before checking for the Access-Control-Allow-Origin headers?
There Are Two Approaches to Getting It Right.Use a reverse proxy server or WSGI server(such as Nginx or Apache) to proxy requests to your resource and handle the OPTIONS method in the proxy. Add support for handling the OPTIONS method in the resource's code.
If you want to bypass that restriction when fetching the contents with fetch API or XMLHttpRequest in javascript, you can use a proxy server so that it sets the header Access-Control-Allow-Origin to *. If you need to enable CORS on the server in case of localhost, you need to have the following on request header.
If the server is under your control, add the origin of the requesting site to the set of domains permitted access by adding it to the Access-Control-Allow-Origin header's value. You can also configure a site to allow any site to access it by using the * wildcard. You should only use this for public APIs.
The reason CORS isn't working is that your link gives a "301 Moved Permanently" without a CORS header, redirecting to another link.
The link it redirects to sends the header, however it seems CORS has already given up the preflight on the first response.
Passing back a "Access-Control-Allow-Origin" header with the 301 may solve your problem, that should allow the preflight to continue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With