I have a LOCAL HTML file which contains JSON HTTP Request to a server. Although the request works in IE, it fails on chrome raising the error :
Access to XMLHttpRequest at ' http://SERVERNAME/QuestionnaireExample/METHODNAME ' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
The XMLHTTP code which raises the error is:
$.support.cors = true;
//upload the questionnaire
$.ajax({
url: 'http://SERVERNAME/QuestionnaireExample/METHODNAME',
type: 'GET',
success: function (result) {
// CODE for success
},
error: function (result) {
// CODE for error
}
});
});
Diagnostic of the network shows:
Request URL: http://SERVERNAME/QuestionnaireExample/METHODNAME
Request Method: GET
Status Code: 401 Unauthorized
Remote Address: [::1]:80
Referrer Policy: no-referrer-when-downgrade
Provisional headers are shown
Accept: */*
Origin: null
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36
As I mentioned, in IE the same code works from local file
$.support.cors = true;
//upload the questionnaire
$.ajax({
url: 'http://SERVERNAME/QuestionnaireExample/METHODNAME',
type: 'GET',
success: function (result) {
// CODE for success
},
error: function (result) {
// CODE for error
}
});
});
It's simply not allowed by browsers to perform a cors request from a local file. It must be run from a webserver. If you open a file like 'C:\\temp.html' and run the script there, this error will occur. If you however, open it from ' http://localhost/temp.html ', the cors request can be allowed, given that the receiving server allows cors requests and you send a cors request prior to sending the ajax request. I'm not sure if your line $.support.cors = true; is enough to enable cors for that specific request. Could be that this line enables it globally but you still need to attach a cors header to the ajax 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.