Here's the my front Ajax code
let ii = 0
function dothisone(e) {
e.preventDefault();
ii++
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function() {
if(this.readyState === 4) {
console.log( this.responseText);
console.log('Ajax ran: ', ii, 'Times');
}
});
xhr.open("POST", "http://localhost:3000/api/");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send();
console.log('You hit the button: ', ii, 'Times');
}
And here's my backend code in node js
var http = require('http');
var url = require('url');
let numt = 0;
http.createServer(function (req, res) {
numt++;
res.writeHead(200, {
'Content-Type': 'text/html',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS, PUT, PATCH, DELETE',
'Access-Control-Allow-Headers': 'content-type, Accept, Authorization',
'Access-Control-Allow-Credentials': false,
});
var q = url.parse(req.url, true);
var txt = q.year + " " + q.month;
console.log('Backend got',numt,'hit(s)');
res.end(txt);
}).listen(9000);
console.log for every single request / button clickin my backend hits twice and shows
// first request
Backend got 1 hit(s)
Backend got 2 hit(s)
// another request
Backend got 3 hit(s)
Backend got 4 hit(s)
This only occurs every i set this(or any othe header before sending) in the xhr request
xhr.setRequestHeader("Content-Type", "application/json");
please help!!!
I'm using pure node js. No frameworks please. Thanks
Related
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";
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
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
Thank you for reading!
I want to open a PDF from a REST backend that gets loaded via XHR in a new tab with specified filename and Authorization header.
So far I managed to download it with this (incl. auth headers and filename):
// saves XHR stream as file with configurable filename
downloadXHRFile:function(endpoint,data,method,filename,errorcallback,mimetype){
bsLoadingOverlayService.start();
var def = $q.defer();
var token = localStorageService.get('token');
var xhr = new XMLHttpRequest();
xhr.open(method, CONFIG.URL+endpoint, true);
xhr.setRequestHeader('Authorization', 'Bearer '+token);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
if (this.status == 200) {
var blob=new Blob([this.response], {type:mimetype});
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download=filename;
link.click();
bsLoadingOverlayService.stop();
}else{
bsLoadingOverlayService.stop();
errorcallback(xhr.statusText);
}
def.resolve();
};
xhr.send(
JSON.stringify(data)
);
return def;
},
Further I managed to open it in a new tab with the following code (incl. auth headers).
Unfortunately the URL (and by that the filename) looks like this:
blob:http://localhost:3000/0857f080-d152-48c6-b5fb-6e56292db651
Probably it can be solved somehow like above but I cant find the solution.
Does someone have a clever idea how I could set the filename in the new Tab?
// opens XHR filestream in tab
openXHRFile: function(endpoint,filename,errorcallback){
var token = localStorageService.get('token');
var our_url = CONFIG.URL+endpoint;
var win = window.open('_blank');
downloadFile(our_url, function(blob) {
var url = URL.createObjectURL(blob);
win.location = url;
});
function downloadFile(url, success) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.setRequestHeader("Authorization", 'Bearer '+token);
// xhr.setRequestHeader('Content-Type', 'application/json');
xhr.responseType = "blob";
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (success) success(xhr.response);
}else{
}
};
xhr.send(null);
}
},
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"