简体   繁体   中英

No response to POST from webUI to Node.JS

I'm hitting a brick wall trying to understand the disconnect between the Ajax POST to Node.JS and the express() response to it.. For example:

Client:

var posting = $.post( "http://localhost:3000/put/requestList" , { first_name: "John", last_name: "Mensa", gender : "Male" })
    .done(function( data ) {
  $( "#schemesdisplay" ).append("Response sent!");
});

Server:

//configure body-parser for express
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());

//allow express to access our html (index.html) file
app.get('/ui/index.html', function(req, res) {
res.sendFile(__dirname + "/" + "index.html");
});
app.post('/put/requestList', function(req, res){
 response = {
  first_name : req.body.first_name,
  last_name : req.body.last_name,
  gender: req.body.gender
 };
 res.end(JSON.stringify(response + "Server Responds!"));
});
var server = app.listen(3000, function(){
var host = server.address().address;
var port = server.address().port;
console.log("Example app listening at http://%s:%s", host, port);
});

In my server's console, I can see the data submitted by the client. However, there is no indication that the server has responded, let alone how to get it back into the div I need the response to be in.

Ideally, I need to send JSON blocks from UI to Node.JS server and back. However getting this simple communication up with two totally different environments has proven to be a challenge.

Any (helpful) suggestions would be much appreciated. Thank you!

You need to replace this line

res.end(JSON.stringify(response + "Server Responds!"));

with this

res.json(response);

res.end() will end the response process. This method actually comes from Node core, specifically the response.end() method of http.ServerResponse. It is used to quickly end the response without any data.

You may also need to change your jQuery post code to include the headers to post json:

$.ajax({
    type: "POST",
    url: "http://localhost:3000/put/requestList",
    data: JSON.stringify({ first_name: "John", last_name: "Mensa", gender : "Male" }),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(data){
        $( "#schemesdisplay" ).append("Response sent!");
    },
    failure: function(errMsg) {
        $( "#schemesdisplay" ).append("ERROR!");
    }
});

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