2

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 ?

2
  • You need to have express js or similar library for http requests. Commented Oct 11, 2018 at 15:31
  • Basically, you are trying to make http request but you dont have anything that corresponds to that request in your node js. Commented Oct 11, 2018 at 15:34

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

It tell me that app isn't defined
It is express js. You need to install it into your project with npm
I modified it for pure node.
0

You are missing the protocol from your URL. Add http:// to it and it should work.

var url = "http://127.0.0.1:8080";

5 Comments

What is the address in the address bar? It should also start with http://127.0.0.1:8080 so that CORS is not needed (would be same-origin)
Are you sure that your JavaScript is not cached and that the version with "http://" URL is loaded?
If the page's origin is http://127.0.0.1:8080 and your AJAX request's origin is http://127.0.0.1:8080, then they are the same origin and not cross-origin, and CORS is not needed. Try it in another browser and see if you get a more helpful error message.
Maybe the error is caused by the fact that my html and js files are on a local path like file\\\c:/Desktop/prj ... ?
Yes. That is most likely the case. Use node.js to serve up your files so that they are from the server listening at 127.0.0.1:8080 and not your file system. Something like express would be convenient for that.