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";
Related
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
I'm trying to create an Outlook add-in for my Organization (Office ProPlus subscription). I am successfully able to hit the /me, /findMeetingTimes, /getSchedule and other APIs (https://learn.microsoft.com/en-us/graph/outlook-calendar-concept-overview).
I'd like to get a new access_token every time it expires, but am struggling to reach the token API to obtain new access_token using a refresh token from my javascript call.
I'm able to hit the API https://login.microsoftonline.com/common/oauth2/token over postman, and get a perfect response:
Response:
{
"token_type": "Bearer",
"scope": "Calendars.ReadWrite Calendars.ReadWrite.Shared Contacts.ReadWrite Contacts.ReadWrite.Shared Files.ReadWrite.All Mail.ReadWrite Mail.ReadWrite.Shared Mail.Send People.Read.All profile User.Read User.ReadWrite openid email",
"expires_in": 3599,
"ext_expires_in": 3599,
"access_token": "eyJ0eXAiOiJKV1QiLCJub25jZSI6IkFRQUJBQUFBQUFDNXVuYTBFVUZnVElGOEVsYXh0V2pUaGVqcWYwNDNiZF9RZjQ5a1NxQnMub25taWNyb3NvZnQuY29tIiwidXRpIjoiUWJ5NnNSRkcya3VtZFVLZUFFZlhBUSIsInZlciI6IjEuMCIsIndpZHMiOlsiNjJlOTAzOTQtNjlmNS00MjM3LTkxOTAtMDEyMTc3MTQ1ZTEwIl0sInhtc19zdCI6eyJzdWIiOiJMS2VIdEdZb1FPSFlrTjNvenAxeVp6Y1BmLWgzT2NiV2ZpWVBEOFpBYUNnIn0sInhtc190Y2R0IjoxNTQzMjM1Mzk3fQ.f8OtUmkpz88JXwrLEeFj1aDV6L6Pm1W6-zPdqHjNaCej8OV6v.......(rest of the token)........FQ9A2APQuErfSljCYFFbsDzh5pvYYtwbbTT4TqnUSczEND2yWmgEONmF4tZUXFoFz49q0Z69rWSb-iJ_C0mQ",
"refresh_token": "OAQABAAAAAAC5una0EUFgTIF8ElaxtWjTqne9aI0dwA5LgpuS878-78FMJrAfgwgXMWiA5KC5WE2......(rest of the token)......XMpn34b0TKU74LdeGTo3lTS0VGlY1FzJ729QH0Nmcg5k86aOesnk2essqoMskUKOY1Wq8d6C75JVd385LzVBsOvjpRVzcZ26htbToV40U5wQ9R20ejpLiCgAnxFlDsS9pG-0huTPlGaeSZS5kYECrDpWapyv4TckEnXPWWGVOeZIdaf6HB41IhNJ6OYy_HFbDFmlu2TqGQhRadNB827B87cbcOdARZyHc-"
}
However when i try the exact same request in my javascript:
var data = "client_id=<client_id>&scope=user.read%20calendars.readWrite.shared%20mail.send&refresh_token=<refresh_token>&redirect_uri=https%3A%2F%2Flocalhost%3A3000%2F&grant_type=refresh_token&client_secret=<client_secret>";
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function (responseText) {
if (this.readyState === 4 && this.status == 200) {
console.log(responseText);
document.getElementById("startTime").innerHTML = "Success " + xhr.response; //Setting an add-in field to success, just as indicator
}
else{
document.getElementById("startTime").innerHTML = "Error " + xhr.response; //Setting an add-in field to success, just as indicator
}
});
xhr.open("POST", "https://login.microsoftonline.com/<tenant-id>/oauth2/token");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
xhr.setRequestHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE');
xhr.setRequestHeader('Access-Control-Allow-Headers', 'Content-Type');
xhr.send(data);
I get an empty response:
Error
If I try a xhr.responseXML instead, I get:
Error null
What am I doing wrong? Is there a sample javascript/ajax call to https://login.microsoftonline.com/common/oauth2/token API?
Stuck on this for quite some time, any help or suggestions would be hugely appreciated!
Could not find any help on the forums
Thanks and Cheers 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
I am calling API to return a JSON with all needed objects (notes):
$( document ).ready(function() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
var response = xhr.responseText;
//do stuff with response
}
xhr.open('GET', 'http://mydomain:8080/notes/all', true);
xhr.send(null);
});
HTTP request:
#RequestMapping(value = {"/all"}, method = RequestMethod.GET, produces = "application/json")
public #ResponseBody List<Note> getAllNotes() {
return noteService.getAllNotes();
}
When I run locally on Mac, everything works. My Response header has Content-Type: application/java, and Request accepts it.
However, when I upload my .war to Ubuntu 16.04 server, Request header's Content-Type changes to txt/html, and I get
404 Page Not Found
.
I am using tomcat8.5.5 on both machines.
How do I specify/change the Request Header Content-Type?
Images of headers:
running on remote
and local
I noticed that I had <script src="noteAPI.js"></script> declaration in BOTH index.html and notes.html. I have removed this declaration from index.html and it worked!
I'm integrating an intranet with a document management system. The DMS has a SOAP API. We've built a client that receives REST calls, makes the SOAP calls, and returns JSON or document data.
The problem is all of the solutions for AJAX filedownload seem to use iFrame (see John Culniver's filedownload plugin).
I can't use this because I need to provide authentication credentials in the header. The only other potential solution I can think of is using window.open (if I can get past browser popup blocking).
Does anyone have another potential solution or how might do this with window.open??
Thanks
I don't think there is a client-side solution for this problem. window.open isn't going to let you set the request headers. You'll need to do something like send a cookie or some other value to the server and add server-side code that alleviates the need for the request header.
See the answers to:
Offer a generated file for download from jQuery post
How to set a Header field on POST a form?
I was able to do it successfully. I'm my example I'm using Basic Authentication however you can replace your Authorization header with different value (e.g you can replace it with Bearer Yourtokenvalue.
Here is the code snippet
$(document).on("click", "#btn", function() {
var username = "yourUserNameForBasicAuthentication";
var password = "yourPasswordForBasicAuthentication"
console.log("button clicked");
var request = new XMLHttpRequest();
request.open("GET", $("#txtUrl").val().trim(), true);
//Set the authorization headers
request.setRequestHeader("Authorization", "Basic " + window.btoa(username + ":" + password));
//Set the Response type as blob which means raw data
request.responseType = "blob";
//We will initiate a default file name in case no file name is detected later on from headers of HTTP Request
var fileName = "unnamed.pdf";
request.onload = function(event) {
if (request.status == 200) {
console.log("success response received");
var blob = request.response;
//Getting contenttype from response headers
var contentType = request.getResponseHeader("content-type");
if (contentType == null) {
contentType = "application/pdf";
}
//Check 'Content-Disposition' header to get filename of file (if possible)
if (request.getResponseHeader("Content-Disposition")) {
var contentDisposition = request.getResponseHeader("Content-Disposition");
fileName = contentDisposition.substring(contentType.indexOf("=") + 1);
}
if (window.navigator.msSaveOrOpenBlob) {
// Internet Explorer
window.navigator.msSaveOrOpenBlob(new Blob([blob], {
type: contentType
}), fileName);
} else {
var el = document.createElement("a");
document.body.appendChild(el);
el.href = window.URL.createObjectURL(blob);
el.download = fileName;
el.click();
el.remove();
window.URL.revokeObjectURL(el.href);
}
} //end of Status code
else {
alert("System failed to authenticate");
}
} //End of event
request.send();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" value="https://yoursamplefile.txt" id="txtUrl" style="width:100%" /><br />
<input type='button' value='Download File' id='btn' />