从客户端向Node.js发送POST请求

3
为了学习node.js,我创建了一个非常简单的留言板应用程序。基本上只有一个评论表单和以前评论的列表。目前该应用程序仅在客户端运行,并且项目存储在本地存储中。
我的目标是将项目发送到Node,然后使用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”参数中放置什么网址导致的。或者整个构建过程可能只是使用了错误的方法。
我还尝试了实现此处描述的方法,但也没有成功。
如果有人能够分享一些关于如何使其工作(从客户端向节点发送POST请求并返回)或分享任何好的教程的提示,那将非常有帮助。谢谢。

2
请看我的问题:https://dev59.com/CWLVa4cB1Zd3GeqPxpa9 - karaxuna
4个回答

3
我刚刚创建了您想要尝试的框架,只是一个客户端和服务器之间的 JSON 数据连接,并且它已经可以工作了。您可以在下面检查代码。
服务器端:

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
 }


0

您可以使用另一个回调函数。

只需添加以下内容即可

response.addListener('end', function(){
    console.log('done')
    // Now use post data.
});

读取帖子数据后。

我遇到了同样的问题,然后它起作用了


0
使用socket.io进行通信。 在客户端和服务器之间的通信中,使用emit()和on()方法。 例如:如果您想从客户端向服务器发送post数据,在客户端侧,使用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
        });
    });

0
我强烈推荐使用Node.js的socket.io模块(http://socket.io/)。它使建立连接和来回传递数据变得非常容易!它是基于事件驱动和非阻塞的。

我知道socket.io,但我没能让它工作。客户端代码无法读取包含的socket.io脚本文件。但也许我会再试一次。 - Maverick

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接