Reputation:
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":"[email protected]","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 ?
Upvotes: 2
Views: 508
Reputation: 581
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.
Upvotes: 2
Reputation: 69
You are missing the protocol from your URL. Add http:// to it and it should work.
var url = "http://127.0.0.1:8080";
Upvotes: 0