为了学习node.js,我构建了一个非常简单的留言簿应用程序。基本上只有评论表格和先前评论的列表。目前,该应用仅限客户端,项目存储在本地存储中。
我想要做的是将项目发送到节点,我将使用Mongo DB保存它们。
问题是我还没有找到一种方法来建立连接,使用POST请求在客户端和node.js之间来回发送数据。
在服务器端,我已经为请求添加了监听器并等待数据:
request.addListener('data', function(chunk) {
console.log("Received POST data chunk '"+ chunk + "'.");
});
在客户端,我使用简单的AJAX请求发送数据:
$.ajax({
url: '/',
type: 'post',
dataType: 'json',
data: 'test'
})
目前这根本不起作用。可能是我不知道在AJAX请求'url'参数中放置什么URL。或者整个事情可能只是使用错误的方法构建。
我也尝试过实现here所描述的方法,但也没有成功。
如果有人可以分享一些如何使这项工作(从客户端发送POST请求到节点并返回)或分享任何好的教程,这将非常有用。谢谢。
答案 0 :(得分:2)
我刚创建了你想在客户端和服务器之间尝试json数据连接的skiliton,它可以检查下面的代码
服务器端:
var http = require("http");
var url = require("url");
var path = require("path");
var ServerIP = '127.0.0.1',
port = '8080';
var Server = http.createServer(function (request , response) {
console.log("Request Recieved" + request.url);
var SampleJsonData = JSON.stringify([{"ElementName":"ElementValue"}]);
response.end('_testcb(' + SampleJsonData + ')'); // this is the postbackmethod
});
Server.listen(port, ServerIP, function () {
console.log("Listening..." + ServerIP + ":" + port);
});
客户端:
jQuery.ajax({
type: 'GET',
url: 'http://127.0.0.1:8080/',
async: false,
contentType: "text/plain", // this is the content type sent from client to server
dataType: "jsonp",
jsonpCallback: '_testcb',
cache: false,
timeout: 5000,
success: function (data) {
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error ' + textStatus + " " + errorThrown);
}
});
}
function _testcb(data) {
//write your code here to loop on json data recieved from server
}
答案 1 :(得分:0)
我强烈推荐node.js(http://socket.io/)的socket.io-module。 它使建立连接和传递数据非常容易! 它适用于事件驱动和非阻塞。
答案 2 :(得分:0)
您可以使用其他回调。
只需添加此
即可response.addListener('end', function(){
console.log('done')
// Now use post data.
});
阅读后期数据。
我遇到了同样的问题而且工作正常
答案 3 :(得分:0)
使用socket.io进行此操作。 对于客户端和服务器之间的通信,请使用emit()和on()方法。 例如:如果要将发布数据从客户端发送到服务器,则在客户端发出带有post参数的事件。现在在服务器端创建一个事件监听器,它监听客户端发出的同一事件。 在客户端:
socket=io();
$('form').submit(function(){
var param1=$('param1').val();
...
socket.emit('mypost',param1);
});
在服务器端:
var io=socket(require('http').Server(require('express')()));
io.on('connection',function(client){
client.on('mypost',function(param1){
//...code to update database
});
});