xmlHttpRequest returns status 0 - javascript

I can't get xmlHttpRequest to return any status but 0. The responseText is always empty. No matter, which url I am opening, this happens. Could someone tell me what I am doing wrong?
var url = "http://stackoverflow.com/";
var xmlHttp = new XMLHttpRequest();
var response = document.getElementById("response");
xmlHttp.open("GET", url, true); // true for asynchronous
xmlHttp.send(null);
xmlHttp.onreadystatechange = function() {
response.innerHTML = xmlHttp.status;
};
https://jsfiddle.net/6ub7ct6j/
Thanks in advance

Check the console. You're trying to load an http resource from an https page, and the browser is blocking it. However, if you try https://stackoverflow.com, you'll get a CORS error.
stackoverflow.com doesn't allow access via Ajax:
VM94:1 XMLHttpRequest cannot load https://stackoverflow.com/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://fiddle.jshell.net' is therefore not allowed access.

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

Chrome Extension blocked from a rails API

I am just trying to talk with a REST api on a Rails site.
I am using a Chrome extension and javascript to make a CORSRequest.
I get this error whenever I try to make a request:
XMLHttpRequest cannot load https://MYWEBSITE.com/api/login. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'chrome-extension://mychomreextensioncode' is therefore not allowed access. The response had HTTP status code 404.
Here is my current code:
function makeCorsRequestLogin() {
var url = "https://MYWEBSITE.com/api/login";
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-type', 'application/json');
xhr.onload = function() {
var text = xhr.responseText;
var title = text; //getTitle(text);
alert('Response from CORS request to ' + url + ': ' + title);
};
if (!xhr) {
alert('CORS not supported');
return;
}
xhr.onerror = function() {
alert('Woops, there\'s an error making the request.');
};
var password = document.getElementById("password").value;
var user_name = document.getElementById("username").value;
xhr.send(JSON.stringify({"user_name":user_name, "password":password}));
}
Elsewhere, in the past, people have said that this code solves it. But, I have no idea where this could would go.
# This is used to allow the cross origin POST requests made by confroom kiosk app.
def set_access_control_headers
headers['Access-Control-Allow-Origin'] = "*"
headers['Access-Control-Request-Method'] = %w{GET POST OPTIONS}.join(",")
end
I am only working in JS and HTML on a chrome extension. I do not have access to the ruby site. Can I solve this problem from only my end?
You should define permission for your server domain in the manifest.json.
"permissions": ["https://MYWEBSITE.com/*"]
Also make sure you set the right protocol whether it's http or https.

Cross-subdomain request

I need to make a cross subdomain request. There is a classic asp site which create an XMLHttpRequest to my PL/SQL Oracle webpage.
The asp site has the domain: test/site.asp and the PL/SQL webpage has the domain test:7779/site... so the top level domain is the same
This is my XmlHttpRequest:
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.onload = function() {
if (xmlHttp.readyState === 4) {
if (xmlHttp.status === 200) {
createChart(divID, xmlHttp.responseText, counter);
} else {
console.error("error");
}
}
};
xmlHttp.open( "GET", theUrl);
xmlHttp.setRequestHeader( "pragma", "no-cache" );
xmlHttp.send( null );
No error occurs in IE11, but in Chrome:
XMLHttpRequest cannot load http://test:7779/site
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://test' is therefore not allowed access.
The response had HTTP status code 501.
Is there a solution to make a cross subdomain request? Maybe with an iframe in my asp site, to get the content?
UPDATE:
I know tried to set the document.domain at both sides to the same: test. But this also didn't solved the problem.
My suggestion is, why dont you use MSXML2.ServerXMLHTTP object, as you have Classic ASP in hand? So that XMLHttp request will be sent from server to server and not from browser.
You can use it like this,
Dim xmlhttp
Set xmlhttp = Server.CreateObject("MSXML2.ServerXMLHTTP")
xmlhttp.setTimeouts 30,500,1000,1000
xmlhttp.Open "GET", "http://yourlink" & time, false
On Error Resume Next
xmlhttp.Send
If Err.Number Then
getBBstatus = "Could Not Retrieve Data"
Err.Clear
Else
getBBstatus = xmlhttp.ResponseText
' Do something with the response here
End If
On Error Goto 0
Set xmlhttp = nothing
Hope it helps, thanks.

Requesting Google Place API with xhr got CORS issue

On my webpage I have some javascript code to query Google Place API (GET) for response. Here's my code look like:
// Sending XHR request
var url = 'https://maps.googleapis.com/maps/api/place/textsearch/json?query=KPMG+Seattle&key=<<MY_KEY>>';
var xhr = createCORSRequest('GET', url);
xhr.setRequestHeader('Access-Control-Allow-Headers', '*');
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
xhr.send();
//**********************//
// Create the XHR object.
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
}
else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
}
else {
// CORS not supported.
xhr = null;
}
return xhr;
}
I am running this local HTML file in my browser, and got CORS error:
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.
I am wondering what the problem can be (I added Access-Control-Allow-Origin to request header)? According to the Google Tutorial this should be enough to make a request?
Please help point out where I am doing wrong... Thanks!
Please see this post XMLHttpRequest Origin null is not allowed
Basically there is a security feature you need to disable to allow XHR of different origin if you are running from a local file.
See the first answer in the post.

Does bitly API support CORS?

I saw in their documentation that CORS is supported. But my attempts to make request from JavaScript have no success.
Requesting this URL:
https://api-ssl.bitly.com/v3/shorten?longUrl=https://google.com/&access_token=token&domain=bit.ly&format=json&languageCode=en-US
I receive standard error :
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://google.com' is therefore not allowed access.
UPD: bitly documentation - http://dev.bitly.com/cors.html
If anyone still having this issue. The reason this happen is because the option (preflight) response from bitly doesn't include 'Access-Control-Allow-Origin' header.
to get around this I used XMLHttpRequest which doesn't send preflight.
let xhr = new XMLHttpRequest();
let url = 'https://api-ssl.bitly.com/v3/shorten?longUrl=https://google.com/&access_token=token'
xhr.open('GET', url);
xhr.onreadystatechange = function() {
if(xhr.readyState === 4) {
if(xhr.status===200) {
console.log(xhr.responseText)
} else {
console.log(xhr)
}
}
};
xhr.send();
It is actually mentioned in bitlly's documentation

Categories

Resources