Access-Control-Allow-Origin Apache SVN endpoint - javascript

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"

Related

Browser claims No 'Access-Control-Allow-Origin' header is present on the requested resource

EDIT2: GETs don't send JSON data. That's my problem. Working on sending it at URL data. It's not letting me delete this post either.
EDIT: I figured out that it's not a preflight problem using developer tools and the network tab. The issue is that the JSON data is not being sent for the GET but it is for the POST. The lack of the Origin header was because the lambda was crashing when it was trying to read the JSON data from the request. Added a try/except block to catch that but I have no clue why the data isn't being sent.
Browser claims No 'Access-Control-Allow-Origin' header is present on the requested resource.
The code below is an AWS Lambda which is behind an AWS REST API Gateway.
POSTs work but GETs throw this error -
Access to XMLHttpRequest at 'https://my_url.amazonaws.com/dev/quark/customers' from origin 'http://localhost:8081' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
They're configured exactly the same and logs(CloudWatch) show that the header is being set properly.
import logging
def lambda_handler(event, context):
logging.getLogger().setLevel(logging.INFO)
logging.info(event["headers"]["Origin"])
response = {
'statusCode': 200,
'headers':
{
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
'Access-Control-Allow-Credentials': True,
'Access-Control-Allow-Origin': event["headers"]["Origin"],
'Access-Control-Allow-Methods': 'POST,GET,DELETE,PATCH'
},
'isBase64Encoded':False,
'body': ""
}
logging.info(response)
return response
Both of these CURLs work but only the POST works in the browser(using JS for that, included for reference)
curl -X POST -H 'Authorization: Basic API_AUTH_KEY' -H "Cache-Control: no-cache" https://my_url.amazonaws.com/dev/quark/customers -d #./data_for_testing/customer.json
curl -X GET -H 'Authorization: Basic API_AUTH_KEY' -H "Cache-Control: no-cache" https://my_url.amazonaws.com/dev/quark/customers -d #./data_for_testing/customer.json
function send()
{
var ItemJSON;
ItemJSON = '{ "customer_info": { "customer_shortname":"WU2", "deploy_pending": "ams,arn,dal,fra,gru,iad,lax,lcy,lga,nrt,sin,sjc,syd" }, "object_type":"customer"}';
URL = "https://my_url.amazonaws.com/dev/quark/customers"
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = callbackFunction(xmlhttp);
xmlhttp.open("GET", URL, false);
xmlhttp.setRequestHeader("Content-Type", "application/json");
//xmlhttp.setRequestHeader('Authorization', 'Basic API_AUTH_KEY'); //in prod, you should encrypt user name and password and provide encrypted keys here instead
xmlhttp.onreadystatechange = callbackFunction(xmlhttp);
xmlhttp.send(ItemJSON);
alert(xmlhttp.responseText);
document.getElementById("div").innerHTML = xmlhttp.statusText + ":" + xmlhttp.status + "<BR><textarea rows='100' cols='100'>" + xmlhttp.responseText + "</textarea>";
}
function callbackFunction(xmlhttp)
{
//alert(xmlhttp.responseXML);
}
</script>
<html>
<body id='bod'><button type="submit" onclick="javascript:send()">call</button>
<div id='div'>
</div></body>
</html>
Authorization is disabled until I can get the CORS response to work properly.
I've tried both Chrome and Firefox to see if they get the same behavior and they do.
I'm only setting the Origin header to what's in the request for dev purposes, an asterisk does not make it work.
I've been doing a bunch of reading and since this is a GET without authorization, it should not need the preflight but it seems to still access it when I make the GET calls.
[pic of console/network tab][1]
[1]: https://i.stack.imgur.com/rolGy.png
GET requests from the browser will get a pre-flight request first. Try adding "OPTIONS" to your list in Access-Control-Allow-Methods. Also make sure any rules / firewall in front of the request is allowing OPTIONS queries.

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

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.

unable to set 'Access-Control-Allow-Origin' header

I need to access my web api hosted remotely from my react app. On the server side i did below to allow cross domain communication:
import javax.ws.rs.core.Response;
import com.mypackage.ResponseDto;
#Override
public Response fetch(String id, String env) throws ServiceException
{
ResponseDto res = new ResponseDto();
res = updateResp(id, env); // not important
return Response.ok().header("Access-Control-Allow-Origin","*").entity(res).build();
}
When i check from postman i can see cors header correctly set as below:
access-control-allow-origin →*
content-type →application/json
date →Wed, 16 Aug 2017 11:07:16 GMT
server →web
transfer-encoding →chunked
But when i access the same endpoint from react app, browsers starts complaining with below error:
Fetch API cannot load
http://myservices.com/myservice-app/services/. 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. If an opaque response serves your needs, set the request's
mode to 'no-cors' to fetch the resource with CORS disabled
Any idea whats going on here?
Edit#1
Did below change still see the same error:
return Response.ok()
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "POST, GET, PUT, UPDATE, OPTIONS")
.header("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With")
.entity(response).build();
I have no experience with whatever Java library you're using, but something like this must work:
#Override
public Response options() throws ServiceException
{
ResponseDto res = new ResponseDto();
return Response.ok().header("Access-Control-Allow-Origin","*").entity(res).build();
}
If the library works like I think it does, this will send a 200 OK on every OPTIONS request you send to your server, with header Access-Control-Allow-Origin = *. That's what you should be aiming for.

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.

Javascript: How do I setRequestHeader for Access-control-Allow-Origin BEFORE http.open?

Techies--
I've been going around in a circle, alternating between the error:
https://anyurlwithcreds.com/x?$format=JSON&$top=2. 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. The response had HTTP status code 403.
when the javascript looks like this:
HTTPSFResponse.open("GET", "https://anyurlwithcreds.com/x?$format=JSON&$top=2", true);
HTTPSFResponse.setRequestHeader('Access-Control-Allow-Origin', '*');
HTTPSFResponse.setRequestHeader('Access-Control-Allow-Methods', 'GET');
HTTPSFResponse.setRequestHeader('Access-Control-Allow-Headers', 'Content-Type');
...and the error :
'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.
...when the code looks like this;
HTTPSFResponse.setRequestHeader('Access-Control-Allow-Origin', '*');
HTTPSFResponse.setRequestHeader('Access-Control-Allow-Methods', 'GET');
HTTPSFResponse.setRequestHeader('Access-Control-Allow-Headers', 'Content-Type');
HTTPSFResponse.open("GET", "https://anyurlwithcreds.com/x$format=JSON&$top=2", true);
Clearly I am missing something. Either I've misunderstood Access-Control-Allow-Origin's role as a header in CORs or perhaps there's a remote setting necessary on the site that's serving the pages? Please advise on how to solve this.

Categories

Resources