I'm trying to post data to an external website from a wordpress site using Javascript, however when i send the form i'm getting this:
XMLHttpRequest cannot load https://external_site.com/embed/documents.
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://my_site.com' is therefore not allowed access.
The response had HTTP status code 404
I'm trying to this from a Wordpress site, this is the Javascript part that sends the data
jQuery('#send_doc').click(function(){
var url = jQuery('#document_url').val();
var name = jQuery('#name').val();
var request = new XMLHttpRequest();
request.open('POST', 'https://external_site.com/embed/documents');
request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Authorization', 'Token my_token
request.onreadystatechange = function () {
if (this.readyState === 4) {
console.log('Status:', this.status);
console.log('Headers:', this.getAllResponseHeaders());
console.log('Body:', this.responseText);
}
};
var body = {
'document_url': url,
'name': name
};
request.send(JSON.stringify(body));
});
My question is, i understand that this is a Cross-domain problem, but my question is: Can i resolve the problem by my side or is this problem just on the externa site side?
Thank you very much for your answers
Related
I am trying to connect to Denodo to pull back information via an API call, but I have to go through Data Power for security reasons. When bypassing Data Power, we are able to successfully retrieve the data from Denodo. I have been informed that everything is set up in Data Power correctly for the response headers and the configuration is set to allow our web application. Below is the code we use to make the call:
var xhr = new XMLHttpRequest();
xhr.open("GET", "target URL", true);
xhr.withCredentials = true;
xhr.setRequestHeader('Access-Control-Allow-Origin', 'source URL');
xhr.setRequestHeader('Access-Control-Allow-Credentials', 'true');
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.response);
console.log(xhr.responseText);
console.log(JSON.parse(xhr.responseText));
}
};
xhr.send();
We receive the following error in the console when executing the function:
Access to XMLHttpRequest at 'target URL' from origin 'source URL' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.
We have tried a variety of different options to get this to work, but we still can't. I've searched the forums for similar issues, and the responses have been tried unsuccessfully.
I'm trying to make a script that will automate something for me and my goal is to make an HTTP request and grab the "set-cookie" that is in the response's headers.
I understand why it's not accessible when done from a normal web page (httpOnly and all) but I am doing it from the background script in a chrome extension.
I tried using both fetch and xhr but they both didn't show me the set-cookie header in the response.
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (xhr.readyState === 4) {
console.log("headers", xhr.getAllResponseHeaders()); // doesnt return httpOnly headers
}
};
xhr.open("GET", 'https://' + host, true);
xhr.send();
or
fetch('https://' + host, {method: 'GET'})
Is there any way to get permission to read those headers? Maybe I need to use something other than fetch? Any help would be greatly appreciated.
This question already has answers here:
XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header
(11 answers)
Closed 3 years ago.
I'm trying to call an API in JavaScript, if I write it in the URL bar, it works but if I use my code, it has CORS policy problem. I don't have any access to the server and I should find a way to solve in the client side.
This is my code:
var xhr = new XMLHttpRequest();
var url = 'http://api.openweathermap.org/data/2.5/weather?q=London&APPID=My-API-Key';
xhr.open('GET', url, true);
xhr.withCredentials = true;
xhr.setRequestHeader("APPID", "MY API Key");
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Origin', '*');
//console.log(json);
xhr.send();
xhr.onload = function () {
if (xhr.status != 200) {
alert(`Error ${xhr.status}: ${xhr.statusText}`);
} else {
alert(`Done, got ${xhr.response.length} bytes`);
}
};
xhr.onprogress = function (event) {
if (event.lengthComputable) {
alert(`Received ${event.loaded} of ${event.total} bytes`);
} else {
alert(`Received ${event.loaded} bytes`); // no Content-Length
}
};
xhr.onerror = function () {
alert("Request failed");
};
</script>
and it has the error:
Access to XMLHttpRequest at 'https://api.openweathermap.org/data/2.5/weather?q=London&APPID=My-API-key' from origin 'https://localhost:44399' has been blocked by CORS policy: 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'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
Anybody has Idea how to solve this error? where should I send my Origin or anything else as a header to get the correct response from the server?
I should handle it in the client side and also I have written the Origin * in the header but still not working.
Best Regards
have you tried to use the "allow-origin: *" Header on your server ?
It's maybe the cause of the problem (your server doesn't accept theses requests)
I have a site hosted on https:// in which I want to pull data from the site which shows the properties of the shares. The URL which returns the data is:
http://ir1.euroinvestor.com/asp/ir/xmlirmultiiso2.aspx?companyid=281191
The code which I have developed to get the data is as follows:
function GetSharesUpdate(){
// makeing AJAX calls to the web service for getting the share update
var xhr = new XMLHttpRequest(); // Set up xhr request
xhr.open("GET", "http://ir1.euroinvestor.com/asp/ir/xmlirmultiiso2.aspx?companyid=281191", true); // Open the request
xhr.responseType = ""; // Set the type of response expected
xhr.send();
// Asynchronously wait for the data to return
xhr.onreadystatechange = function () {
if (xhr.readyState == xhr.DONE) {
var tempoutput = xhr.responseXML;
alert(tempoutput);
}
}
// Report errors if they happen
xhr.addEventListener("error", function (e) {
console.error("Error: " + e + " Could not load url.");
}, false);
}
I am getting the error on the statement xhr.send(); which is as below:
Mixed Content: The page at 'https://[SiteUrl]' was loaded over HTTPS,
but requested an insecure XMLHttpRequest endpoint
'http://ir1.euroinvestor.com/asp/ir/xmlirmultiiso2.aspx?companyid=281191'.
This request has been blocked; the content must be served over HTTPS.
If I change the URL to https i.e.
https://ir1.euroinvestor.com/asp/ir/xmlirmultiiso2.aspx?companyid=281191
then xhr.send(); is executed without any error but I am getting xhr.responseXML null.
What should I make changes in my code to make it working?
The first problem is you are doing ajax request to non-https domain but your domain has SSL installed.
The second problem is Cross origin request CORS, you will have this problem even you solve first (ie. even you try ajax request from non-http domain).
Since you are requesting data from another website this is most likely to happen unless the requested server is configured to serve requests for you domain
To solve this you need to call the data from your server(proxy server) or have the requested server configured to allow requests from your domain.
See more - https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
I'm dealing with some Access-Control-Origin issues when using webworkers to make an XMLHttpRequest.
The issue is easily reproducible in this code, main.js:
var worker = new Worker('js/createSimplePage.js');
worker.onmessage = function () {
console.log('message recieved');
};
And js/createSimplePage.js:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
console.log(xmlhttp.responseText);
}
};
xmlhttp.open("GET", "http://search.twitter.com/search.json?q=balling&rpp=20&callback=", true);
xmlhttp.setRequestHeader('Content-Type', 'text/plain');
xmlhttp.send();
If I include createSimplePage.js in the header of index.html, it runs fine and prints the correct response from the twitter API. However, if I only load main.js and let it try to load createSimplePage.js as a web worker then I receive the error:
XMLHttpRequest cannot load http://search.twitter.com/search.json?q=balling&rpp=20&callback=.
Origin file:// is not allowed by Access-Control-Allow-Origin.
A similar error occurs when hosting the files on SimpleHTTPServer except the error is then
"Origin http://127.0.0.1:8000 is not allowed by Access-Countrol-Allow-Origin."
I don't understand why loading it as a web-worker would break it so it can't access the API.
I don't think webworkers have the same security level as the browser. Maybe you could ensure you scripts are returned with allow all origins header:
header("Access-Control-Allow-Origin: *");
and probably best to removed your custom header:
xmlhttp.setRequestHeader('Content-Type', 'text/plain');
This site has more information:
http://enable-cors.org/