Daisy PENG
Daisy PENG

Reputation: 21

CORS issue in Jquery with GET method

I am working on getting a data through a URL with GET method available. I have used the Jquery to get the JSON and parse it into HTML table.

However, I cannot fix the CORS issue. I have added the code:

res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header('Access-Control-Allow-Credentials', 'True');
res.header('Access-Control-Allow-Headers', 'accept, content-type, x-parse-application-id, x-parse-rest-api-key, x-parse-session-token');

I have also installed the chrome extension to enable CORS.

However, none of them worked. I have also tried to use XMLHttpRequest directly, it still doesn't work...

Here is my code using Jquery:

<!DOCTYPE html>
<html>
<head><meta charset="utf-8"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
 var url = 'https://www.probancemail.com/rest/v2/stats/RT1-PREM_DE?&token=5eX8dIljx9fWOvFu7WO22uL3EEYSN8PEciwZKdYqKxK6HOsHxjyYQpVBQiSLEGOJkId9wTNOAUpGRPfPWJgXV5u8s9EUL9hVeGSa'
function FIXCORS(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header('Access-Control-Allow-Credentials', 'True');
res.header('Access-Control-Allow-Headers', 'accept, content-type, x-parse-application-id, x-parse-rest-api-key, x-parse-session-token');
 // intercept OPTIONS method
if ('OPTIONS' == req.method) {
  res.send(200);
}
else {
  next();
}
};
$(document).ready(function () {
$.getJSON(url,
function (json) {
tr = $("<tr></tr>")
for (var i = 0; i < json.results.length; i++) {
var td = "<td>" + json.results[i].address_components[0].long_name+"</td>"
$(tr).append(td);
}
$('table').append($(tr));
});
});
</script>
</head>
<body>
<table></table>
</body>
</html>

It always shows the error message of No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

And is my code using HTTP Request directly, which is based on this article: https://www.html5rocks.com/en/tutorials/cors/

<!DOCTYPE html>
<html><meta charset="utf-8"/>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>

function reqListener() {
console.log(this.responseText);
}
// 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;
}

// Helper method to parse the title tag from the response.
function getTitle(text) {
return text.match('/campaign');
}

// Make the actual CORS request.
function makeCorsRequest() {
// This is a sample server that supports CORS.
var url = 'https://www.probancemail.com/rest/v2/stats/RT1-PREM_DE?&token=5eX8dIljx9fWOvFu7WO22uL3EEYSN8PEciwZKdYqKxK6HOsHxjyYQpVBQiSLEGOJkId9wTNOAUpGRPfPWJgXV5u8s9EUL9hVeGSa';

var xhr = createCORSRequest('GET', url);
if (!xhr) {
alert('CORS not supported');
return;
 }

 // Response handlers.
xhr.onload = function() {
var text = xhr.responseText;
var title = getTitle(text);
alert('Response from CORS request to ' + url + ': ' + title);
 };

xhr.onerror = function() {
alert('Woops, there was an error making the request.');
};
 xhr.send();
}
</script>
</head>
<body>

<div id = "div"></div>
<button type = "button" onclick = "makeCorsRequest">Retrieve Report Data</button>

</body>
</html>

This one doesn't have error message but has no outcome at all... Is there anyone have some thoughts? Any feedback is welcomed!!! Thanks a lot in advance!

Upvotes: 0

Views: 2778

Answers (1)

hmnzr
hmnzr

Reputation: 1430

CORS should be supported on the server. In case of sending cross-domain request, jQuery adds Origin: http://example.com header to request and expects Access-Control-Allow-Origin: http://example.com or Access-Control-Allow-Origin: * header in response.

You can read more about CORS at MDN: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

P.S. Regarding FIXCORS function in your script, I assume you have copied that from some Node.js CORS guide, it should be place on the server as well

Upvotes: 1

Related Questions