0

I'm using node.js and JQuery to communicate. Whenever I send a post request to my node.js express server, it receives the request but does not seem to give a response.

Client code:

     $("#submitdetails").click(function(){
  $.post("http://neztorian.xyz:26/",
    {
        name: "Donald Duck",
        city: "Duckburg"
    },
    function(data, status){
        alert("Data: " + data + "\nStatus: " + status);
    });

});

Sever code:

var express = require('express');
var app = express();
var bodyParser = require('body-parser');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
console.log("Running");
app.post('/', function (req, res) {
console.log(req.body);

res.send("recieved");

})
app.listen(26);

The server receives the post request and logs it to console but the alert message does not appear on the client. Thank you for your help. Sorry if this is a stupid question.

Edit: Thank you for your answers. Problem was: Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://neztorian.xyz:26' is therefore not allowed access. I've fixed the issue by adding that header to the server.

Neztore
  • 3
  • 8
  • What is `#submitdetails` ? Is it part of a form and page is refreshing? If so need to prevent default action in click or submit handler. Also use error handler on the ajax to get more detail – charlietfl Oct 07 '17 at 12:58
  • Check the console in your browser, you will probably see something like `No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://neztorian.xyz:26' is therefore not allowed access.` – rckrd Oct 07 '17 at 13:17
  • Then read: [why-does-my-javascript-get-a-no-access-control-allow-origin-header-is-present](https://stackoverflow.com/questions/20035101/why-does-my-javascript-get-a-no-access-control-allow-origin-header-is-present) , [no-access-control-allow-origin-header-is-present-on-the-requested-resource-whe](https://stackoverflow.com/questions/43871637/no-access-control-allow-origin-header-is-present-on-the-requested-resource-whe) – rckrd Oct 07 '17 at 13:18

1 Answers1

0

The request is not allowed by the browser because the server is not sending the Access-Control-Allow-Origin header.

Set the header and request are allowed.

app.post('/', function (req, res) {
  console.log(req.body);
  res.header('Access-Control-Allow-Origin', 'http://neztorian.xyz:26'); 
  res.send("recieved");
});

Read more here: CORS

rckrd
  • 3,124
  • 1
  • 13
  • 23