CORS - No 'Access-Control-Allow-Origin' header is present - javascript

I'm hosting a website that has a number of different domain names pointing at it.
lets call the hosted website example.com and the url-forwarded domain names - example-x.com, example-y.com, example-z.com
When the url-forwarded domains are visited, cross domain requests are made back to the host site, example.com.
I'm currently making ajax GET requests to json files and receiving the following error;
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://example-x.com' is therefore not allowed
access.
Even though the preflight OPTIONS return a status of 200 and the GET method returns a status of 200.
OPTIONS;
GET
I have set the following CORs headers on the host htaccess;
# <IfModule mod_headers.c>
SetEnvIfNoCase Origin "https?://(www\.)?(example-x\.com|example-y\.com|example-z\.com)(:\d+)?$" ACAO=$0
Header set Access-Control-Allow-Origin %{ACAO}e env=ACAO
Header set Access-Control-Allow-Methods "GET, PUT, POST, DELETE, OPTIONS"
Header set Access-Control-Allow-Headers "DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range"
Header set Access-Control-Allow-Credentials true
# </IfModule>
And i'm call GET using the following ajax request;
var createCORSRequest = function(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open(method, url, true);
} else if (typeof XDomainRequest !== "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
};
var url = 'http://example.com/data.json';
var xhr = createCORSRequest('GET', url);
xhr.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
xhr.setRequestHeader('Accept', 'application/json, text/javascript');
xhr.onload = function() { console.log('success');};
xhr.onerror = function() { console.log('error'); };
xhr.send();
EDIT
Removing setRequestHeader("Content-Type", "application/json; charset=UTF-8") from the ajax request has removed the preflight requirement, however the CORs error still persists, the screenshot below shows the request / response of GET, its my guess that the correct htaccess headers have not been set on the RequestURL - http://example.com/cms/wp-content/uploads/2017/04/preloader_data.json
GET - WITHOUT OPTIONS PREFLIGHT

You are trying to retrieve a json by a GET request. This should be a simple request, and it does not need to have a preflight request.
If you look at the requirements for a preflight request from MDN, you can see that setting Content-Type other than application/x-www-form-urlencoded, multipart/form-data or text/plain will cause this preflighted request.
If you look at the content-type from the RFC, it is a "SHOULD" for "a message containing a payload body". But your get request does not have a payload. As a result remove that header from your ajax call.

Related

Getting Error while calling external api end point using javascript

I am new to JavaScript and i am trying to send api request from JavaScript.
I am getting below error while calling external endpoint from JavaScript.
from origin 'null' has been blocked by CORS policy: Request header field x-api-key is not allowed by Access-Control-Allow-Headers in preflight response.
var url = "<external_api_for_graphQl"
var api_key = "<api_key>"
var xhr = new XMLHttpRequest();
xhr.open("POST", url, false);
xhr.setRequestHeader("x-api-key", api_key);
xhr.send("");
alert(xhr.status);
any idea how we can resolve this?
Thanks
try to set header
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.setRequestHeader("Access-Control-Allow-Credentials", "true");
xhr.setRequestHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
xhr.setRequestHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
The Access-Control-Allow-Headers header is sent by the server to let the client know which headers it supports for CORS requests. The value of Access-Control-Allow-Headers should be a comma-delineated list of header names, such as "X-Custom-Information" or any of the standard but non-basic header names (which are always allowed).
This error occurs when attempting to preflight a header that is not expressly allowed (that is, it's not included in the list specified by the Access-Control-Allow-Headers header sent by the server). To fix this, the server needs to be updated so that it allows the indicated header, or you need to avoid using that header.
one think you can try is this:
$.ajax({
headers: { "Accept": "application/json", "x-api-key":"<x-api-key>"},
type: 'POST',
url: '<external_api_for_graphQl>',
crossDomain: true,
beforeSend: function(xhr){
xhr.withCredentials = true;
},
success: function(data, textStatus, request){
console.log(data);
}
});

Access-Control-Allow-Origin Apache SVN endpoint

I would like to make a XmlHttp GET request from client Javascript to a Apache SVN endpoint and I'm facing the following error:
Failed to load http://IP_ADDRESS/svn/: Response to preflight request
doesn't pass access control check: No 'Access-Control-Allow-Origin'
header is present on the requested resource. Origin
'http://IP_ADDRESS:3000' is therefore not allowed access.
I've tried set the Header set Access-Control-Allow-Origin "*" in the following files and no success so far.
/etc/apache2/mods-available/dav_svn.conf (the configuration is inside this file)
.htaccess (inside the endpoint root folder)
I'm running out of ideias how to do it.
The Javascript request code:
var xmlhttp = new XMLHttpRequest();
// encodedData = ...
xmlhttp.open('GET', url, true);
xmlhttp.setRequestHeader("Authorization", "Basic " + encodedData);
xmlhttp.withCredentials = true;
xmlhttp.send();
What am I doing wrong?
Have you tried adding the address of the client instead of *?
Header set Access-Control-Allow-Origin "http://IP_ADDRESS:3000"
Also if it doesn't work I would suggest adding these other options:
Header set Access-Control-Allow-Credentials "true"
Header set Access-Control-Allow-Methods "POST,GET,OPTIONS,PUT,DELETE"
Header set Access-Control-Allow-Headers "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"

can not load local xml file through xmlhttprequest

I am using XAMPP Apache on port 80.
When I try with localhost in the url I get:
XMLHttpRequest cannot load http://localhost/ice_escape/pokus.xml. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
and also:
Uncaught TypeError: Cannot read property '0' of null
I tried allowing CORS by adding this to httpd.conf to no avail:
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Max-Age "1000"
Header always set Access-Control-Allow-Headers "X-Requested-With, Content-Type, Origin, Authorization, Accept, Client-Security-Token, Accept-Encoding"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Then I tried changing localhost to 127.0.0.1. It removes the first error, but the other error persists.
var url = "http://127.0.0.1/iceescape/pokus.xml";
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
if (xmlhttp) {
xmlhttp.open("GET", url, true);
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
txt = xmlhttp.responseText;
{//---- some code that parses the xml
var strWidth = "width";
var a = txt.indexOf(strWidth);
a += strWidth.length;
txt = txt.slice(a,(txt.length) );
var width = txt.match(/\d+/)[0];// here it says its null
}
}
}
};
xmlhttp.send();
the xml:
<?xml version="1.0" encoding="UTF-8"?>
<map width = "2400" height = "1800">
<ghost type="troll" speed="5">
<point>
{100,200}
</point>
<point>
{350,250}
</point>
</ghost>
What you are trying to read with XHR is not a local file.
You have origin null (which means your HTML document is a local file, loaded via the file:// URL scheme) and you are making the Ajax result to http://localhost/ice_escape/pokus.xml which is an HTTP resource on the same computer.
Load your HTML document from the web server too.

Requesting Google Place API with xhr got CORS issue

On my webpage I have some javascript code to query Google Place API (GET) for response. Here's my code look like:
// Sending XHR request
var url = 'https://maps.googleapis.com/maps/api/place/textsearch/json?query=KPMG+Seattle&key=<<MY_KEY>>';
var xhr = createCORSRequest('GET', url);
xhr.setRequestHeader('Access-Control-Allow-Headers', '*');
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
xhr.send();
//**********************//
// Create the XHR object.
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
}
else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
}
else {
// CORS not supported.
xhr = null;
}
return xhr;
}
I am running this local HTML file in my browser, and got CORS error:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'null' is therefore not allowed access. The response had HTTP status code 405.
I am wondering what the problem can be (I added Access-Control-Allow-Origin to request header)? According to the Google Tutorial this should be enough to make a request?
Please help point out where I am doing wrong... Thanks!
Please see this post XMLHttpRequest Origin null is not allowed
Basically there is a security feature you need to disable to allow XHR of different origin if you are running from a local file.
See the first answer in the post.

XMLHttpRequest changes POST to OPTION

i have this code:
net.requestXHR = function() {
this.xhr = null;
if(window.XMLHttpRequest === undefined) {
window.XMLHttpRequest = function() {
try {
// Use the latest version of the activex object if available
this.xhr = new ActiveXObject("Msxml2.XMLHTTP.6.0");
}
catch(e1) {
try {
// Otherwise fall back on an older version
this.xhr = new ActiveXObject("Mxsml2.XMLHTTP.3.0");
}
catch(e2) {
//Otherwise, throw an error
this.xhr = new Error("Ajax not supported in your browser");
}
}
};
}
else
this.xhr = new XMLHttpRequest();
}
net.requestXHR.prototype.post = function(url, data) {
if(this.xhr != null) {
this.xhr.open("POST", url);
this.xhr.setRequestHeader("Content-Type", "application/json");
this.xhr.send(data);
}
}
var rs = new net.requestSpeech();
console.log(JSON.stringify(interaction));
rs.post("http://localhost:8111", JSON.stringify(interaction));
when the send execute, i have this log:
OPTIONS http://localhost:8111/ [HTTP/1.1 405 Method Not Allowed 74ms]
And in localhost:8111 i have a reslet serverResource that accept post, it is problem of same origin policy? i have modify the restlet to put the allow-origin header and i test it with another GET http request (in jquery) and work ok. I have the problem of same origin resolve because i use an html5 browser and my server put the headers in the response, so why the send shows me this error? why change POST for OPTION?
Thanks!
Possible duplicate?: I think no, but it's true, the problem is the
same for both questions, but mine are refers since the question that
there is an issue with the browser, and the other, first points to
jquery. By experience the time does not count for duplicate, the
answers are different but it's true that both questions complement
each other.
Yes, this is a "problem with same-origin policy". You are making your request either to a different server or to a different port, meaning that it is a cross-site HTTP request. Here is what the documentation has to say about such requests:
Additionally, for HTTP request methods that can cause side-effects on
server's data (in particular, for HTTP methods other than GET, or for
POST usage with certain MIME types), the specification mandates that
browsers "preflight" the request, soliciting supported methods from
the server with an HTTP OPTIONS request method, and then, upon
"approval" from the server, sending the actual request with the actual
HTTP request method.
There is a more detailed description in the CORS standard ("Cross-Origin Request with Preflight" section). Your server needs to allow the OPTIONS request and send a response with Access-Control-Allow-Origin, Access-Control-Allow-Headers and Access-Control-Allow-Methods headers allowing the request. Then the browser will make the actual POST request.
I was having this exact problem from a JavaScript code that sent an ajax content.
In order to allow the Cross-Origin Request with Preflight I had to do this in the .ASPX that was receiving the petition:
//Check the petition Method
if (Request.HttpMethod == "OPTIONS")
{
//In case of an OPTIONS, we allow the access to the origin of the petition
string vlsOrigin = Request.Headers["ORIGIN"];
Response.AddHeader("Access-Control-Allow-Origin", vlsOrigin);
Response.AddHeader("Access-Control-Allow-Methods", "POST");
Response.AddHeader("Access-Control-Allow-Headers", "accept, content-type");
Response.AddHeader("Access-Control-Max-Age", "1728000");
}
You have to be careful and check what headers are being asked by your petition. I checked those using Fiddler.
Hope this serves someone in the future.
Answer:
Your browser is initiating a PreFlight OPTIONS request.
Why:
Because your request is not a simple request.
Why it is not a simple request:
Because of "Content-Type" = "application/json".
Solution:
Try to use either of below content types :
application/x-www-form-urlencoded
multipart/form-data
text/plain
As others have pointed out, this is a CORS thing.
This is how to handle it in NGINX (based on this source):
location / {
if ($request_method = OPTIONS ) {
add_header Access-Control-Allow-Origin "http://example.com";
add_header Access-Control-Allow-Methods "GET, OPTIONS";
add_header Access-Control-Allow-Headers "Authorization";
add_header Access-Control-Allow-Credentials "true";
add_header Content-Length 0;
add_header Content-Type text/plain;
return 200;
}
}
If you want to allow CORS requests from any origin, replace,
add_header Access-Control-Allow-Origin "http://example.com";
with
add_header Access-Control-Allow-Origin "*";
If you don't use authorization, you won't need this bit:
add_header Access-Control-Allow-Headers "Authorization";
add_header Access-Control-Allow-Credentials "true";
For the API I'm developing I needed to whitelist 3 request methods: GET, POST and OPTIONS, and an X-App-Id header, so this us what I ended up doing:
if ($request_method = OPTIONS ) {
add_header Access-Control-Allow-Origin "*";
add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";
add_header Access-Control-Allow-Headers "X-App-Id";
add_header Content-Length 0;
add_header Content-Type text/plain;
return 200;
}

Categories

Resources