response not getting with the header in javascript - javascript

I'm new to AJAX and I have the following code:
function get_filesize(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open("HEAD", url, true);
xhr.onreadystatechange = function() {
if (this.readyState == this.DONE) {
callback(parseInt(xhr.getResponseHeader('Access-Control-Allow-Credentials')));
}
};
xhr.send();
}
get_filesize("http://fileraja.com/download/?songURL=./Tamil/K/Kaththi_160kbps/Pakkam_Vanthu-StarMusiQ.Com.mp3", function(size) {
var estimatedtime = (new Date().getTime())/size;
var time = new Date(estimatedtime);
console.log(time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds());
});
When I run this code, I get an error like:
XMLHttpRequest cannot load http://fileraja.com/download/?songURL=./Tamil/K/Kaththi_160kbps/Pakkam_Vanthu-StarMusiQ.Com.mp3. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
After some research, I have found that it's due to the CORS policy, so I tried adding the code xhr.setRequestHeader("Access-Control-Allow-Credentials",true);, but it didn't help me.
How can I get rid of this error?

After some search i have found that its due to CORS policy...so i have tried adding the code...
You can't do anything client-side that will change the CORS policy of the server. This is the point of the SOP and CORS: The server determines whether to allow any particular client to grab its content via ajax.
So unless http://fileraja.com are willing to add the relevant CORS headers at their end, you simply cannot do cross-origin requests to their domain with ajax. You might ask them, or ask if they offer a JSONP API (JSONP isn't subject to the SOP, because it's not ajax). Otherwise, you'll have to use a server of your own to proxy the request.

This error is because of the CORS(Cross Origin Resource Sharing) Policy which does not allow requests that do not arise from the same origin. A header Access-Control-Allow-Headers: * can be set at the resource to allow all requests.
Other methods include JSONP as mentioned by T.J Crowder and the same server for proxy request.
This might be a good read CORS and POST Request

Related

Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error while the header is given

I'm trying to get informations from a SystemLinkServlet.
So I tried to execute this JavaScript code from a Nintex Forms (Sharepoint) :
var http = new XMLHttpRequest();
var url = 'www.exampleservlet.com';
var params = "anyxml"
http.open('POST', url, true)
http.setRequestHeader('Content-type', 'application/xml');
http.setRequestHeader('Access-Control-Allow-Origin', '*');
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
};
http.send(params);
But I still got this error in my console :
Access to XMLHttpRequest at 'www.exampleservlet.com' from origin 'www.exampleorigin.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
It seems that the header is ignored or maybe I can't set multiple request headers?
It works on Postman.
Update
So It worked with an extension but apparently, I can't set headers with JavaScript code in my Nintex Forms.
I'm trying to find to pass those headers without using an extension.
If you are using PHP, try adding the following code at the beginning of the php file:
If you are using localhost, try this:
header("Access-Control-Allow-Origin: *");
If you are using external domains such as server, try this:
header("Access-Control-Allow-Origin: http://www.webiste.com");
Also you I suggest you to use this extension:
https://chrome.google.com/webstore/detail/cors-unblock/lfhmikememgdcahcdlaciloancbhjino?hl=en
Postman or other similar tools provide you development environments. In this way, you can ignore and pass CORS rule while sending request and getting response by changing tool settings. But if you sending request via browser(chrome, firefox etc.), browsers always add some preflight controls.
For example, browser send options message to get server side rule before your http request. So that invalid or wrong requests are blocked by browser before processing your http request.
In your case, server side must include your domain information. You can not change this communication rule from client side by adding just "Access-Control-Allow-Origin: *" or "Access-Control-Allow-Origin: http://www.webiste.com" statements.

When tried to convert to base64 from url - getting CORS Issue in JS

when i tried to convert image url to base64 am getting CORS issue.
Not sure what exactly need to do to get rid of this CORS issue
my code look like this
function toDataURL(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function() {
callback(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
}
toDataURL('https://www.dropbox.com/******/gradient-test.jpg?dl=1', function(dataUrl) {
console.log('RESULT:', dataUrl)
})
am getting this error
Access to XMLHttpRequest at 'https://www.dropbox.com/****/gradient-test.jpg?dl=1' from origin 'https://stackoverflow.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.**
and am not able to console ,since CORS issue.
Can any guys help me to get rid with an jsfiddle or an live example
The CORS issue you are facing is because you are trying to access the www.dropbox.com domain from a different domain. The short answer is that you can't fix this from your own domain--it requires cooperation from the www.dropbox.com domain to fix this. You are the client in this case, and dropbox is the server, so as a client you can't tell the server what security settings to use. The server can opt in and could configure their site to allow your origin, but that isn't something dropbox is likely to do. You'll need to re-architect your approach. (also see Ways to circumvent the same-origin policy if you don't believe me when I say you need to re-architect your approach.)
Check out https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS for more background:
For security reasons, browsers restrict cross-origin HTTP requests
initiated from scripts. For example, XMLHttpRequest and the Fetch API
follow the same-origin policy. This means that a web application using
those APIs can only request resources from the same origin the
application was loaded from unless the response from other origins
includes the right CORS headers.
You could try using JavaScript to inject a script tag into your DOM that sets the type of the script tag to something other than JavaScript. Then you could have your code read the contents of that and make use of it...but that is a completely re-architected approach. See How does HTML tags work inside script tag? and https://stackoverflow.com/a/8578840/230055 if you want to look into that.

If CORS if refusing my API request and I don't control the server, is there nothing I can do? [duplicate]

This question already has answers here:
XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header
(11 answers)
Closed 3 years ago.
So as I understand it, the person who hosts content on their server can set CORS headers which specify who can access this content and what they can do with it. The owner can also prevent certain sites from accessing these items by only allowing specific sites through using the Access-Control-Allow-Origin header.
Is any of that correct, or have I misunderstood how CORS works?
I am trying to access information from a server I do not control and am receiving the CORS error below. I am using the API provided by the owners, but I'm making requests from my localhost dev server and wonder if this might be causing issues? I am developing using Quasar and Vue and I'm very, very new to developing generally - please excuse any obvious mistakes/oversights.
Here's my code:
var data = null;
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener('readystatechange', function () {
if (this.readyState === this.DONE) {
console.log(this.responseText);
}
});
xhr.open('GET', 'url');
xhr.setRequestHeader('X-Correlation-Id', 'id');
xhr.setRequestHeader('content-type', 'something+json; UTF-8');
xhr.setRequestHeader('authorization', 'Basic username:password');
xhr.send(data);
And I'm receiving this:
Access to XMLHttpRequest at 'url' from origin 'http://localhost:8080' 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.
I have almost no idea what this means, and I have done a fair bit of reading trying to understand it. If there is an obvious fix, please go the step further to explain it to me - thankyou!
You can always use a CORS proxy like cors-anywhere or you could even make your own.

Dailymotion JS API - No 'Access-Control-Allow-Origin' header is present on the requested resource

I'm currently trying to retrieve videos from a private Dailymotion channel in my personal application.
To do that I'm trying to authenticate to the Dailymotion API using the grant_type method : password.
Here is my POST request :
xhr.open('POST', 'https://api.dailymotion.com/oauth/token', true);
xhr.setRequestHeader('Content-Type', 'multipart/form-data');
xhr.onload = function(e) {
console.log("HEADERS", e.target.getAllResponseHeaders())
if (e.target.status < 400) {
console.log(e);
} else {
console.log("error")
}
};
xhr.onerror = function(e) {
console.log("HEADERS", e.target.getAllResponseHeaders())
};
xhr.send('grant_type=password&client_id=<MyAPIKey>&client_secret=<MyAPISecret>&username=<MyUserName>&password=<MyPassword>');
I'm receiving the following error : No 'Access-Control-Allow-Origin' header is present on the requested resource.
I checked the response header and the Access-Control-Allow-Origin is missing. I cannot add this parameter on the API server because I'm requesting Dailymotion servers...
So my question is : Is it possible to configure the Dailymotion application (referenced by my API Key) to accept my request from my private domain, or is there a way to bypass the 'Access-Control-Allow-Origin' problem.
Thanks in advance !
It is not possible to by-pass Access-Control-Allow-Origin in common browsers.
Maybe Dailymotion allows only specific domains, or simply disallows localhost
Since the Access-Control-Allow-Origin header (and all the other CORS headers) are response headers, you can't control them.
Is this code running in a browser? If so, confirm that the Origin request header is being sent. If it is not running in a browser, try adding the Origin request header with your request and see if that causes the server to include the CORS response headers.
If that doesn't work, then you can't do anything without possibly using their SDK.

What is wrong with my HTTP over AJAX (javascript)

My code:
var answer_array = [];
var req = new XMLHttpRequest();
req.onload = function() {
answer_array = answer_array.concat(JSON.parse(this.responseText).results);
console.log(answer_array);
}
req.open("GET", "https://api.comettracker.com/v1/gpsdata?fromdate=2015-10-13");
req.setRequestHeader("authorization", "Basic Base64 encoded credentials");
req.setRequestHeader("cache-control", "no-cache");
req.setRequestHeader("postman-token", "b94725ff-408b-c82e-a985-6c38feb380af");
req.send();
This is what is in my console:
scripts2.js:22 OPTIONS https://api.comettracker.com/v1/gpsdata?fromdate=2015-10-13 (anonymous function) # scripts2.js:22
2015-10-21 12:41:09.059 index.html:1 XMLHttpRequest cannot load https://api.comettracker.com/v1/gpsdata?fromdate=2015-10-13. 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.
When I go to the network tab on Chrome I see this:
gpsdata?fromdate=2015-10-13 OPTIONS 405 xhr scripts2.js:22 0 B 452 ms
This error message:
No 'Access-Control-Allow-Origin' header is present on the requested resource
means that you are running into a cross origin permission issue which means that you are trying to access a site that does not permit access from the domain that your page is on. If your page is on your local drive being accessed with a file:// URL, then the first thing you can do is to put it on an actual web server and try it there since file:// URLs have some additional restrictions on them.
If that doesn't work either, then the issue is that the api.comettracker.com site is not allowing access from your particular site.
When I put your code into a jsFiddle and try it there and look at the network trace, what I see there is that the OPTIONS method which is used to pre-flight a cross origin request is being rejected by api.comettracker.com which tells the browser the cross origin request as currently formatted is not permitted.
I get a different error if your custom headers are removed from the request so I think that there's something incorrect about your custom headers. Since I don't know that particular API, don't have your access credentials or know how to use them, I don't know what exactly to suggest for the headers, but I think that's the place to start.

Categories