No 'Access-Control-Allow-Origin' header - Tried all possible solutions - javascript

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...

Related

Why there is cors issue after adding Access-Control-Allow-Origin header at back end?

I'm making an ajax call to a different domain. My team member added the Access-Control-Allow-Origin header to http://localhost:3000 .
$.ajax({
type: 'GET',
url: myurl,
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', 'Bearer '+authorization);
},
crossDomain: true,
// xhrFields: {
// withCredentials: true
// },
contentType: 'application/json',
dataType: 'JSON',
success: function (response) {
if(time_one === 0){
main_result = response;
time_one++;
}
if(response.length==0){
alert("NO Data; Try a valid search")
$('.row3, #paging').hide();
$('.loading-gif').show();
$('#table').html('');
myCallBack(main_result);
}
else{
$('#table').html('')
myCallBack(response);
}
},
error: function(err) {
$('.loading-gif').hide();
$(".pageblocker").hide();
alert('Error: '+JSON.stringify(err));
myCallBack(main_result)
}
});
If I try this way, I'm getting 'Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.' I don't understand why I'm getting such type of error even after adding the ACAO header.
And I also noticed another error if I add the 'withCredentials' attribute.
'Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:3000' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.' I don't understand the difference between those two errors.
The server at myurl must return the Access-Control-Allow-Origin response header.
If you don’t have access to the server environment for the myurl server to configure that server to send the Access-Control-Allow-Origin response header, then you’ll need to make the request through proxy instead. You can find more details on setting up that kind of proxy in the answer at "No 'Access-Control-Allow-Origin' header is present on the requested resource".
Anyway the fact that adding Access-Control-Allow-Origin to the http://localhost:3000 backend has no effect in this case is expected—because Access-Control-Allow-Origin is a response header that must be sent by the server a request is made to. http://localhost:3000 isn’t that—instead it’s the server serving the frontend JavaScript code that’s initiating the request.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS is the best resource for getting an understanding of how all this stuff works. Some other answers here to take a look at:
Angular 2 HTTP POST returns data but goes to error (cors)
Why isn't rack-cors filtering incoming requests, according to Rspec
Will ASP.net Core CORS policy prevent resource access from non-browser requests?
CORS is a double system checking?

JavaScript - 'No Access Control Allow Origin' header' despite one being present

I have a simple PHP file that performs a MySQL query and returns a result.
At the top of the PHP file, I have this code:
<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
?>
I know that this is working as if I were to inspect in Chrome, if I look at the request headers that come back in the 'Network' tab I can see the header was set successfully.
Now I make the call from my JavaScript file on another domain using jQuery:
var getMyResults = $.ajax({
url: "http://mydomain.uk/myphpfile.php",
data: {something: "someData"},
dataType: "JSON",
type: "GET"
});
Every single time I run this code from the JavaScript file I get the follow error:
XMLHttpRequest cannot load http://mydomain.uk/myphpfile.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://myotherdomaincallingthefile.uk' is therefore not allowed access.
Why is this happening?
There is a redirect going on before you get to the final page, which sends the header, locate it; if it is in .htaccess you can add this to the .htaccess file:
<ifModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</ifModule>
or your other option is in your Ajax call to use the final URL, which would supply the headers without any redirects in the way.
After a few hours of investigation I found the issue with the help of t3chguy in the comments.
My AJAX request URL: "http://mydomain.uk/directory"
Correct, working cross origin AJAX: "http://mydomain.uk/directory/"
A single extra "/" fixed the issue.
Why?
With the help of http://redirectcheck.com/ I saw that without the '/' Apache was making a redirect which meant that the cross origin header wasn't present on that initial request, hence the error.

Get part of the content from the website to different one

i want to get the part of the different website page to my website content.
i have tried to do that with sending an ajax request to that webpage , but getting an cross domain access error
have any idea how to do that?
for example, i want to get this part only http://gyazo.com/600ee9facec408dd56a69c907293ebed from this website http://www.simbagames.com/en/aboutus.aspx
to my existing webpage, and put that content in my webpage content part
this is how i was tring to do that
jQuery.ajax({
type:'POST',
url: link,
crossDomain: true,
dataType: "html", // this is important
headers: { 'Access-Control-Allow-Origin': '*' },
success: function (data) {
console.log(data);
}
})
No need iframes
is that possible?
You need to add a header to response in aboutus.aspx. Or like Kasyx says, give up javascript and get with cUrl
"Access-Control-Allow-Origin: *"
Actually you cant because in addition by setting "Access-Control-Allow-Origin: *"
A server supporting CORS must respond to requests with several access control headers:
Access-Control-Allow-Origin: "*"
By default, CORS requests are not made with cookies. If the server includes this header, then we can send cookies along with our request by setting the withCredentials option to true.
Access-Control-Allow-Credentials (optional)
If we set the withCredentials option in our request to true, but the server does not respond with this header, then the request will fail and vice versa.
if server not responding you with the Access-Control-Allow-Origin: "*" then you cant fetch data
more about that

Error Cross Domain calling Json

I'm trying to bring my json file into my HTML but a error Cross Domain is happening:
XMLHttpRequest cannot load http://guardioesdacidadania.com.br/game_temp/assets/js/caratulas.json?jsoncallback=. The request was redirected to 'http://www.guardioesdacidadania.com.br/game_temp/assets/js/caratulas.json?jsoncallback=', which is disallowed for cross-origin requests that require preflight.
I've tried many different solutions but none of them worked.
Here's my js code.
$.ajax({
url: 'http://guardioesdacidadania.com.br/game_temp/assets/js/caratulas.json?jsoncallback=',
headers: { 'Access-Control-Allow-Origin': '*' },
crossDomain: true,
success: function () { alert('it works') },
error: function() {alert('it doesnt work')},
datatype: 'jsonp'
});
For CORS support to work, the server must be configured to respond with the Access-Control-Allow-Origin header, sending the header with your request does nothing. You can see a bit of information on how to get this to work by visiting : Origin is not allowed by Access-Control-Allow-Origin
If you do not have access to the server, then it is not possible to do it via AJAX so you'll need to create some sort of server side proxy to relay the request through.

Why XMLHttpRequest doesn't work with "www."?

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.

Categories

Resources