简体   繁体   中英

Send post request from client to node.js

In order to learn node.js I have built a very simple guestbook app. There is basically just a comment form and a list of previous comments. Currently the app is client side only and the items are stored within local storage.

What I want to do is send the items to node where I will save them using Mongo DB.

The problem is I have not yet found a way to establish a connection to send data back and forth the client and node.js using POST requests.

On the server side I have added listeners to the request and wait for the data:

request.addListener('data', function(chunk) {
    console.log("Received POST data chunk '"+ chunk + "'.");
});

On the client side I send the data using a simple AJAX request:

$.ajax({
    url: '/',
    type: 'post',
    dataType: 'json',
    data: 'test'
})

This does not work at all in the moment. It could be that I don't know what url to place in the AJAX request 'url' parameter. Or the whole thing might just be the build using the wrong approach.

I have also tried implementing the method described here , but also with no success.

It would really help if anyone can share some tips on how to make this work (sending POST request from the client side to node and back) or share any good tutorials. thanks.

i've just created the skiliton that you want to try just a json data connection between client and server and it worked you can check the code below

Server Side :

 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); }); 

Client Side :

 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 } 

i can highly recommend the socket.io-modul for node.js ( http://socket.io/ ). it makes establishing connections and passing data forth and back quite easy! it works event-driven and non-blocking.

You can use another callback.

Just add this

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

after reading post data.

I had the same problem and it worked

Use socket.io for this. For communication between the client and the server, use emit() and on() methods. Eg: If you want to send post data from the client to the server, in the client side, emit an event with the post parameters. Now make an event listener on the server side which listens for the same event which was emitted by the client. On client side:

    socket=io();
    $('form').submit(function(){
    var param1=$('param1').val();
    ...
    socket.emit('mypost',param1);
    });

On server side:

    var io=socket(require('http').Server(require('express')()));
    io.on('connection',function(client){
        client.on('mypost',function(param1){
            //...code to update database
        });
    });

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