简体   繁体   中英

response not getting with the header in 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 TJ Crowder and the same server for proxy request.

This might be a good read CORS and POST Request

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM