Cross-Origin Request Blocked: in javascript using XMLHttpRequest - javascript

I am trying to send a HTTP request in javascript using XMLHttpRequest and so I am using the following code in an HTML file. I have a server running which returns a dictionary of form {'test' : 'string'}.
<script type="text/javascript">
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:5000/test", true);
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.send();
xhr.onreadystatechange = processRequest;
console.log(xhr.status)
function processRequest(e)
{
if (xhr.readyState == 4)
{
alert(xhr.responseText);
}
}
</script>
However in spite of adding the header, I am getting a Cross-Origin Request Blocked: error in my console when I try to print xhr.status in the console it shows 0 as response.
I am using flask server which shows a bad message error on using HTTPS, so I am using an HTTP request.

You can not control CORS from front end. You have to put the CORS module to your back end server.
check the link flask cors.

Related

How to POST json data to the server? (CORS error)

My goal
I am doing .aspx file on Microsoft Visual Studio. What I expect is that the system will scan the QR code and then send the JSON data to the server side.
PS. I am using XMLHttpRequest to send the data.
What I Get
First I tried to pass it directly, it does not work so I check its status and readyStats, what it shows is 1(open) and 0(not initialized) (I am expecting 4(done) and 200(ok)) the responseText is null. I then inspected my browser (Google Chrome), the console shows an error "Access to XMLHttpRequest at 'https://website-A.aspx' from origin 'https://localhost:44371' 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."
What I tried
So I searched for solution on stack overflow, most of them says that I need to put in the header Access-Control-Allow-Origin:* to the server, but the problem is I do not have the control of the server but I do contacted them to change the code to try it out, end up Access-Control-Allow-Origin:* doesn't work so I looked for alternative. I tried to use plugin such as Moesif Origin & CORS Changer but it shows "Access to XMLHttpRequest at 'https://website-A.aspx' from origin 'https://localhost:44371' 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.".
Below is my code:
function onScanSuccess(qrCodeMessage) {
...
var url = "https://Website-A.aspx";
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open("POST", url);
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
console.log(xhr.status);
console.log(xhr.responseText);
}
};
//I hardcoded the data for testing
var data = {
"SOME_ID": "Value",
"SOME_TYPE": "Value",
"SOME_ID": "Value",
"SOME_AMT": "Value",
"SOME_AMT_CURRENCY": "Value",
"SOME_DESC": "Value",
...
};
xhr.send(data);
}
Is there anyway to solve this without changing the server side's code or bypassing the CORS?
I wish to solve this by modify the code in the same .aspx only, is it possible?
If my code ain't going to work, is there any other way to do it?
Any helps will be appreciated.
cors must be allowed on server side. your code looks ok.
sorry, i can't use the comment function yet

How to send Ajax POST request on https

I'm trying to make an Ajax POST request, but I keep getting a 404 error "GET https://www.test.com/login.aspx?ReturnUrl=%2fapi%2ftest%2fsave 404 (Not Found)"
Don't know if it is because the site has https?
This is the code I have used:
var params = { name: "Test"};
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://www.test.com/api/test/save', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
response = JSON.parse(xhr.responseText);
console.log(reponse);
}
};
xhr.send(JSON.stringify(params));
Any suggestions on how to make it work?
What is happening is that your backend / API is set up to require authentication and if a request is received without authentication, it redirects to the login page. You can see this in your error response:
"GET https://www.test.com/login.aspx?ReturnUrl=%2fapi%2ftest%2fsave 404 (Not Found)"
But the other problem is that you don't have a login page! So that explains the 404 Not Found response.
Either disable authentication on your API for testing, or include authentication / credentials in your Ajax request.

how to enable Access-Control-Allow-Headers in xmlhttprequest

An XMLHttpRequest cannot load error arises when using HTML with Jquery to call an API:
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://api.xxxx.com/col?system=xxx&keyid=xxxxx&rtype=city&region=" + citiCd);
xhr.onreadystatechange = function () {
if (this.readyState == 4) {
var datax = JSON.stringify(this.responseText);
//my stuff
}
};
xhr.send(null);
When run, it produces this error:
XMLHttpRequest cannot load
http://api.xxxx.com/col?system=xxx&keyid=xxxxx&rtype=city&region=DLI.
Origin localhost is not allowed by Access-Control-Allow-Origin.
How do I enable access? I tried xdomainrequest without luck.
I've faced that issue a few times and it should be resolved on the server side.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

Ajax - "Access-Control-Allow-Origin" Error

I'm trying to work with the Livestream API to see if a certain channel is live but keep getting this error:
XMLHttpRequest cannot load http://channel.api.livestream.com/1.0/livestatus?channel=huskystarcraft. Origin http://www.webdevstl.com is not allowed by Access-Control-Allow-Origin.
Do I need to run it through PHP or am I doing something wrong in my ajax call? It's pretty straight forward code:
function getActive(){
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var json = JSON.parse(xmlhttp.responseText);
console.log(json);
}
}
xmlhttp.open("GET", "http://channel.api.livestream.com/1.0/livestatus?channel=huskystarcraft", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send();
}
getActive();
You're running into restrictions imposed by the Same Origin Policy. In short, AJAX calls to a different domain are prohibited and will fail - unless explicitly permitted by the remote host.
You need to either use JSONP (mostly applicable to data returned by APIs) or proxy the request through your own server/domain.
CORS would also be an option, but that assumes you having access to the remote server's config.

xmlhttp request status 302

I am trying to write core java script application that can test and analyse the http request. I started with below code. Firebug net tab says 302 status error.
<script type="text/javascript">
$(document).ready(function(){
var req = new XMLHttpRequest();
req.open("GET","http://www.google.com",true);
req.onreadystatechange = statusListener;
req.send(null);
});
function statusListener(req){
if (req.readyState == 4)
{
if (req.status == 200) {
var docx=req.responseXML;
console.log(docx);
}
}
}
</script>
3xx status codes are redirections.
302 means "Found". Quote from w3.org:
The requested resource resides temporarily under a different URI. Since the redirection might be altered on occasion, the client SHOULD continue to use the Request-URI for future requests.
If you want to get the page it redirects to, you have to check the URI in the response headers with the getResponseHeader() method.
You can see here to see how to access the correct URI.

Categories

Resources