I know this question has been asked a lot before, but I literally tried out everything but I'm still getting this error.
I'm trying to fetch json data through ajax in my index.php file.
I'm running my website through apache2 on an ubuntu server. I have no idea where to go from here.
Exact error:
Failed to load http://localhost:32348/getinfo: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
What I tried:
- Adding this to /etc/apache2/apache2.conf File
<ifModule mod_headers.c>
Header set Access-Control-Allow-Origin: *
</ifModule>
- Adding this to in between every <Directory> tag to /etc/apache2/apache2.conf File:
Header set Access-Control-Allow-Origin "*"
- Adding this to my index.php file:
<?php
header('Access-Control-Allow-Origin: *');
?>
- Changing 'json' to 'jsonp', setting crossDomain to true and adding headers to allow origin
function fetchLiveStats() {
$.ajax({
url: api + '/getinfo',
dataType: 'jsonp',
type: 'GET',
crossDomain: true,
headers: {'Access-Control-Allow-Origin': '*'},
success: function(response) {
console.log(response);
},
cache: 'false'
}).done(function(data){
pulseLiveUpdate();
lastStats = data;
currentPage.update();
}).always(function () {
setTimeout(function() {
fetchLiveStats();
}, refreshDelay);
});
}
You need to add the Access-Control-Allow-Origin header to the response from http://localhost:32348/getinfo.
What I tried: - Adding this to /etc/apache2/apache2.conf File
Everything else you've said about your question implies that Apache was hosting the website on port 80, not the one on port 32348. You're changing the wrong server.
A website can't give itself permission to access data that another website will give the owner of the browser.
Changing 'json' to 'jsonp'
Don't use JSONP. It is a dirty hack. (It also requires that http://localhost:32348/getinfo return JSONP, which is almost certainly doesn't).
setting crossDomain to true
That just tells jQuery to not add headers it adds to Same Origin requests in case there is an HTTP redirect to a different origin. This prevents it being a complex request that needs a preflight. Since you aren't requesting a same origin URL in the first place, this does nothing.
adding headers to allow origin
You can't put response headers on the request!
Trying to will turn it into a complex request that requires a preflight, and cause you event more problems.
You need to edit whatever code is responsible for serving http://localhost:32348/getinfo
Don't forget to empty your cache (ipconfig/flushdns) and your browser cache when you try a new update, otherwise, the modifications may not be considered...
I am making a jQuery ajax call from a local file which retrieves JSON data from a webserver:
$.ajax({
type: 'GET',
url: 'http://mywebsite.com/data.json',
dataType: 'json',
success: showData
});
and I am getting the following error on chrome:
XMLHttpRequest cannot load http://mywebsite.com/data.json. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'null' is therefore not allowed access.
I have read through a lot of other answers which seem to come to the conclusion that you cannot make ajax requests from local files with chrome, so the solutions are:
Host the file making the request on the sever
Run chrome with the "--allow-file-access-from-files" flag
but neither of these options are suitable for me.
However, when I host the JSON data on another site (myjson.com), so that the line in the ajax request reads
url: 'https://api.myjson.com/bins/myfile'
the file loads perfectly and the data is correctly displayed.
Why is the ajax request allowed to 'myjson.com' but not to 'mywebsite.com'?
Edit:
I have the line
Header set Access-Control-Allow-Origin "*"
in my apache2.conf file
What you need to do is create a .htaccess file in your document root and add the following lines to it:
<FilesMatch "\.(json)$">
Header set Access-Control-Allow-Origin "*"
</FilesMatch>
What the above lines do is, they allow Cross origin resource sharing for all domains on .json files thus removing the error.
I am doing a jquery post send the data to the php file which is in the same domain.
Here is part of code:
var postData = { "score": score };
$.post("saveScores.php", postData, function() { //ERROR POINTS THIS LINE
.....
});
I am getting this error message: XMLHttpRequest cannot load http://redirect.main-hosting.com/error404.php/8?domain=quiztest.3eeweb.com. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://quiztest.3eeweb.com' is therefore not allowed access.
I have hosted this in a subdomain. I have added Access-Control-Allow-Origin in the headers:
header("Access-Control-Allow-Origin : http://quiztest.3eeweb.com");
But this did not solve the problem.
Is there anything I can do to fix this issue?
Thanks,
I am missing several other headers. You have to add these headers too:
Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: GET, POST, OPTIONS
And of course, check that all the http locations are correct.
Addendum:
Remove the http:// part from Access-Control-Allow-Origin : http://quiztest.3eeweb.com, like Access-Control-Allow-Origin : quiztest.3eeweb.com
It looks like your site host is executing some kind of weird redirect.
This is what the ajax request is trying to load:
http://redirect.main-hosting.com/error404.php/8?domain=quiztest.3eeweb.com
I couldn't tell you why they are doing that, but odds are, its not something you can fix. Find better hosting.
I'm using .htaccess to rewrite urls and I used html base tag in order to make it work.
Now, when I try to make an ajax request I get the following error:
XMLHttpRequest cannot load http://www.example.com/login.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://example.com' is therefore not allowed access.
Use addHeader Instead of using setHeader method,
response.addHeader("Access-Control-Allow-Origin", "*");
* in above line will allow access to all domains.
For allowing access to specific domain only:
response.addHeader("Access-Control-Allow-Origin", "http://www.example.com");
Check this blog post.
Why the error is raised:
JavaScript code is limited by the same-origin policy, meaning, from a page at www.example.com, you can only make (AJAX) requests to services located at exactly the same domain, in that case, exactly www.example.com (not example.com - without the www - or whatever.example.com).
In your case, your Ajax code is trying to reach a service in http://wordicious.com from a page located at http://www.wordicious.com.
Although very similar, they are not the same domain. And when they are not on the same domain, the request will only be successful if the target's respose contains a Access-Control-Allow-Origin header in it.
As your page/service at http://wordicious.com was never configured to present such header, that error message is shown.
Solution:
As said, the origin (where the page with JavaScript is at) and the target (where the JavaScript is trying to reach) domains must be the exact same.
Your case seems like a typo. Looks like http://wordicious.com and http://www.wordicious.com are actually the same server/domain. So to fix, type the target and the origin equally: make you Ajax code request pages/services to http://www.wordicious.com not http://wordicious.com. (Maybe place the target URL relatively, like '/login.php', without the domain).
On a more general note:
If the problem is not a typo like the one of this question seems to be, the solution would be to add the Access-Control-Allow-Origin to the target domain. To add it, depends, of course, of the server/language behind that address. Sometimes a configuration variable in the tool will do the trick. Other times you'll have to add the headers through code yourself.
For .NET server can configure this in web.config as shown below
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="your_clientside_websiteurl" />
</customHeaders>
</httpProtocol>
</system.webServer>
For instance lets say, if the server domain is http://live.makemypublication.com and client is http://www.makemypublication.com then configure in server's web.config as below
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://www.makemypublication.com" />
</customHeaders>
</httpProtocol>
</system.webServer>
If you get this error message from the browser:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '…' is therefore not allowed access
when you're trying to do an Ajax POST/GET request to a remote server which is out of your control, please forget about this simple fix:
<?php header('Access-Control-Allow-Origin: *'); ?>
What you really need to do, especially if you only use JavaScript to do the Ajax request, is an internal proxy who takes your query and send it through to the remote server.
First in your JavaScript, do an Ajax call to your own server, something like:
$.ajax({
url: yourserver.com/controller/proxy.php,
async:false,
type: "POST",
dataType: "json",
data: data,
success: function (result) {
JSON.parse(result);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr);
}
});
Then, create a simple PHP file called proxy.php to wrap your POST data and append them to the remote URL server as a parameters. I give you an example of how I bypass this problem with the Expedia Hotel search API:
if (isset($_POST)) {
$apiKey = $_POST['apiKey'];
$cid = $_POST['cid'];
$minorRev = 99;
$url = 'http://api.ean.com/ean-services/rs/hotel/v3/list?' . 'cid='. $cid . '&' . 'minorRev=' . $minorRev . '&' . 'apiKey=' . $apiKey;
echo json_encode(file_get_contents($url));
}
By doing:
echo json_encode(file_get_contents($url));
You are just doing the same query but on the server side and after that, it should works fine.
You need to add this at start of your php page "login.php"
<?php header('Access-Control-Allow-Origin: *'); ?>
you have to put the headers keys/values in options method response.
for example if you have resource at http://mydomain.com/myresource
then, in your server code you write
//response handler
void handleRequest(Request request, Response response) {
if(request.method == "OPTIONS") {
response.setHeader("Access-Control-Allow-Origin","http://clientDomain.com")
response.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
response.setHeader("Access-Control-Allow-Headers", "Content-Type");
}
}
Basically alter API header response by adding following additional parameters.
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: *
But this is not good solution when it comes to the security
Add this to you PHP file or main controller
header("Access-Control-Allow-Origin: http://localhost:9000");
The workaround is to use a reverse proxy running on your 'source' host and forwarding to your target server, such as Fiddler:
Link here:
http://docs.telerik.com/fiddler/configure-fiddler/tasks/usefiddlerasreverseproxy
Or an Apache Reverse proxy...
Solved with below entry in httpd.conf
#CORS Issue
Header set X-Content-Type-Options "nosniff"
Header always set Access-Control-Max-Age 1728000
Header always set Access-Control-Allow-Origin: "*"
Header always set Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT,PATCH"
Header always set Access-Control-Allow-Headers: "DNT,X-CustomHeader,Keep-Alive,Content-Type,Origin,Authentication,Authorization,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control"
Header always set Access-Control-Allow-Credentials true
#CORS REWRITE
RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
#RewriteRule ^(.*)$ $1 [R=200,L]
RewriteRule ^(.*)$ $1 [R=200,L,E=HTTP_ORIGIN:%{HTTP:ORIGIN}]]
Pleaes find the Function used in XMLHTTPREQUEST in Javascript for setting up the request headers.
...
xmlHttp.setRequestHeader("Access-Control-Allow-Origin", "http://www.example.com");
...
</script>
Reference: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader
I have following code:
var params = {
cache:false,
dataType:"json",
type:"GET",
url: "/order.php",
error: function(data){
dump(data);
},
success: function (data){
alert('ok');
},
data:{
js:1
}
};
$.ajax(params);
So if I run example.com it gets work perfect.
But if I run www.example.com I get an error via my function dump().
Google console shows an error:
XMLHttpRequest cannot load
=1345470451769">http://example.com/order.php?js=1&tariff=247&=1345470451769. Origin
http://www.example.com is not allowed by Access-Control-Allow-Origin
What does it mean?
So I don't need any permanent redirect from www.domain.com to domain.com.
Thanks in advance for any help.
update 1:
I added function:
function getBaseUrl()
{
var baseUrl = '';
baseUrl += location.protocol + '//';
baseUrl += location.hostname;
return baseUrl;
}
and change url: "/order.php" on url: getBaseUrl() + "/order.php"
got the same error.
Am I doing something wrong here?
Update 2:
I added this one to htaccess file:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin http://sample.com http://www.sample.com
</IfModule>
It seems my hosting doesn't support it, because I still get an error for www.
The error you've got there means that you can't make a XMLHttpRequest from one domain to another unless the target domain specifies in its response header that you're allowed to do this. It's a security measure enforced by the browser.
The entire domain has to match, so example.com can't make a XMLHttpRequest request to www.example.com and vice-versa.
You could just use some javascript to get the URL based on the current document location, or use relative paths instead.
Also make sure the webserver isn't doing a silent redirect from one domain to another as this may also cause permissions issues.
The alternative if you have access to the webserver is to add the appropriate cross domain headers to the response - http://www.w3.org/TR/cors/
Example:
Access-Control-Allow-Origin: http://www.example.com http://example.com
Edit: The domains in the above list need to be space separated, not comma.
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "http://sample.com http://www.sample.com"
</IfModule>
Subdomains are considered a different domain with the same origin policy. Use a relative path if you site functions with or without www.
If the server redirects, why is the current page not on www?
From a SEO standpoint, you probably want the server to do the redirects to one version of the url or the other.