CORS issue in Jquery with GET method - javascript

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!

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

Related

Why does 1 out of 10 of my requests returns CORS error in the browser

I currently have a script that makes an ajax request using XMLHttpRequest(). The essence of the script is to keep track of certain analytics and here's how it was implemented.
Adds an event listener and sends data to start_tracking_analytics script
document.addEventListener('DOMContentLoaded', function(){
try{
//url to send data to
var url = 'https://subdomain.domain.com/start_tracking_analytics.php?key='+tracker_key;
//host name
var host = location.protocol + '//' + location.hostname
//send data
sendAnalytics(url, host);
setTimeout(function(){
setInterval(function(){
try{
sendUpdateAnalytics();
}catch(e){
}
}, 7500);
}, 1000);
}catch(e){
}
});
Here's how the sendAnalytics function is implemented
function sendAnalytics(url, host){
try{
var createCORSRequest = function(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Most browsers.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// IE8 & IE9
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
};
var method = 'POST';
var xhr = createCORSRequest(method, url);
xhr.onerror = function() {
// Error code goes here.
};
xhr.send();
}catch(e){
//...
}
}
Here's how sendUpdateAnalytics was implemented. Note: This gets triggered at intervals
function sendUpdateAnalytics(){
try{
//url to send data to
var url = 'https://subdomain.domain.com/end_tracking_analytics.php?id='+tracker_session_id;
//current host
var host = location.protocol + '//' + location.hostname
//send the data
sendData(url, host);
}catch(e){
}
}
Now, to the backend (response) script. i.e - start_tracking_analytics.php && end_tracking_analytics.php
On both scripts, I had this headers set
//GET variables
$host = $_GET["host"];
$key = $_GET["key"];
//set header for CORS
header("Access-Control-Allow-Origin: $host");
header("Access-Control-Allow-Credentials: true");
//I Do all of my computations here and echo an integer
echo 1;
The problem: 1 out of 10 requests made to end_tracking_analytics returns CORS error
Access to XMLHttpRequest at 'https://subdomain.domain.com/end_tracking_analytics.php?id=1&host=https://www.hostUrl.com&key=XXXXX' from origin 'https://www.hostUrl.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I really do hope this is explanatory and will be happy to provide more details if it's not. Any idea why this could be happening?

POST request to Node.js server using ajax

I'm new to Node.js .
I'm trying to do a POST request to my Node.js server running locally on port 8080.
But it doesn't work.
FireFox block my POST request because it is cross-origin
Reason: CORS request not HTTP
Here is my code:
HTML
<html>
<head>
<title>Progetto Start</title>
<script src="..\Controller\Start.js"></script>
</head>
<body>
<input type="button" id="btPostJSON" value="invia JSON" onclick="SendJSON()"/>
</body>
</html>
Start.js:
function SendJSON() {
xhr = new XMLHttpRequest();
var url = "127.0.0.1:8080";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.email + ", " + json.name)
}
}
var data = JSON.stringify({"email":"tomb#raider.com","name":"LaraCroft"});
xhr.send(data);
}
Node js server:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {"Content-Type": "text/html"});
res.write(req.url);
res.end();
console.log(req.url);
}).listen(8080);
I'm printing url to console and as a response only to see if it works
There is someone that has already solved mine problem ?
Just a quick note, CORS is required whenever the domain of the server/api does not match the domain of the calling client. If your port number on the client side does not match the port number on the server/api, the domains do not match and CORS is required
Shamelessly pulled from here: [https://bigcodenerd.org/enable-cors-node-js-without-express/][1]
Inside your createServer callback, put this:
const headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'OPTIONS, POST, GET',
'Access-Control-Max-Age': 2592000, // 30 days
/** add other headers as per requirement */
};
if (req.method === 'OPTIONS') {
res.writeHead(204, headers);
res.end();
return;
}
if (['GET', 'POST'].indexOf(req.method) > -1) {
res.writeHead(200, headers);
res.end('Hello World'); //Replace this with your response logic
return;
}
The if (req.method == "OPTIONS") block is your 'pre-flight' request. This is basically just used to check cors permissions for a resource.
There's also other packages that will do something similar for you. Replace the "*" with your specific client-side hostname ("something.com") for better security. Using the wildcard (*) is a security risk, so before putting something in production, you'll want to change that to whatever domain or ip address you want to let access your api.
You are missing the protocol from your URL. Add http:// to it and it should work.
var url = "http://127.0.0.1:8080";

Javascript CORS "pre-flight"

I'm so desperate because I can't see the light in this endless darkness, the problem is, that there is no way to stop "pre-flight" options response from appearing and of course can't reach certain API, I've been looking and reading stuff about CORS but without luck.
This is the function in the API that should display an array:
function main_get() {
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: SOME-KEY');
header('Access-Control-Max-Age: 1728000');
header("Content-Length: 0");
header("Content-Type: text/plain");
$array['results'] = array(
array(
"adId"=>"8847575",
"make"=>"SOMEMAKE",
"model"=>"Some model",
"year"=>"2008",
"version"=>"The version",
)
);
$this->response($array, 200);
}
I'm using Codeigniter and REST plugin for the API.
Note that the headers are included
This is the code for the request sample:
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
function makeCorsRequest() {
var url = 'http://*****/api/test';
var xhr = createCORSRequest('GET', url);
xhr.setRequestHeader('SOME-KEY', 'dffs54f78v');
if (!xhr) {
document.getElementById("response").innerHTML = 'CORS not supported';
return;
}
xhr.onload = function () {
var text = xhr.responseText;
document.getElementById("response").innerHTML = text;
};
xhr.onerror = function () {
document.getElementById("response").innerHTML = 'Woops, there was an error making the request.';
};
xhr.send();
}
makeCorsRequest();
Got this code from some CORS tutorial in the internet.
And still can't get rid of this:
main.js:40 OPTIONS http://*****/api/test 404 (Not Found)
makeCorsRequest # main.js:40 (anonymous) # main.js:43 localhost/:1
Failed to load http://*****/api/test: Response for preflight has
invalid HTTP status code 404.
What am I doing wrong?
I know there may be an answer somewhere, but I've wasted 3 days at this thing and found nothing.
Thanks in advance

CORS no Acess-Control-Allow-Origin header

In my Javascript file I want to load xml data from this site: https://www.anime2you.de/feed/
But I always get a no Access-Control-Allow-Origin header despite using CORS. Did I misunderstand the concept / usage of CORS or is the website faulty?
My code:
var feeds = ["https://www.anime2you.de/feed/"];
var createCORSRequest = function(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Most browsers.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// IE8 & IE9
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
};
var url = 'https://www.anime2you.de/feed/';
var method = 'GET';
var xhr = createCORSRequest(method, url);
xhr.onload = function() {
alert("success");
};
xhr.onerror = function() {
alert("fail");
};
xhr.send();
Thanks in advance
Nova
Have you set the header("Access-Control-Allow-Origin: *"); on the script you are requesting? https://www.anime2you.de/feed/ if you are using Access-Control-Allow-Origin with a wildcard then set the credentials to false in
xhr.withCredentials = false;
If you can set the domain name of the server making the request i.e
header("Access-Control-Allow-Origin: http://domain-where-js-sits");
then you can do:
xhr.withCredentials = true;
and set these other headers:
Access-Control-Allow-Methods: POST
Access-Control-Allow-Headers: Content-Type
An alternative is to use jsonp - this may not work for you as the response needs to be in json:
function response(data) {
edit the returned data here
}
var script = document.createElement('script');
script.src = 'https://www.anime2you.de/feed/?callback-response';
document.body.appendChild(script);

Need Help to solve ajax issue?

I create safari extension and i inject js in this extension. In this JS code i send ajax call which create following error in console. "Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers"
here is my code:
this function i copied from net to solve cross domain issue but its not working please help me to figure out this.
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR has 'withCredentials' property only if it supports CORS
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") { // if IE use XDR
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
var request = createCORSRequest("get", "https://www.karmora.com/list.xml");
if (request) {
// Define a callback function
request.onload = function () {
};
// Send request
request.send();
}
$.get('https://example.com', function (data) {
alert("Ajax call successfull");
});
Your problem is related with Same-origin_policy
If you have access to the server, add to Apache Web Server virtual host configuration the following settings:
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept"

Categories

Resources