简体   繁体   中英

Ajax to node.js express module isn't giving a response

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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM