[英]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: 我碰到一堵砖墙,试图了解Ajax POST对Node.JS的断开连接和对它的express()响应之间的连接。例如:
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. 但是,没有迹象表明服务器已响应,更不用说如何将其返回到div中了,我需要响应才能进入。
Ideally, I need to send JSON blocks from UI to Node.JS server and back. 理想情况下,我需要将JSON块从UI发送到Node.JS服务器,然后再发送回去。 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. res.end()将结束响应过程。 This method actually comes from Node core, specifically the response.end() method of http.ServerResponse. 该方法实际上来自Node核心,特别是http.ServerResponse的response.end()方法。 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: 您可能还需要更改jQuery邮政编码,以包含用于发布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!");
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.