Saurabh Jhunjhunwala
Saurabh Jhunjhunwala

Reputation: 2922

Passing data from Ajax Post to node js

I am learning node and want to send some data from an Ajax call to node.

Below are my Ajax and node calls.

Ajax Method

function getUserName(){
    var data ={};
    data.email=$('#email').val();
    data.fNmame=$('#fNmame').val();
    data.lName=$('#lName').val();

    $.ajax({
        type: 'POST',
        data: JSON.stringify(data),
        contentType: "application/json",
        dataType:'json',
        url: '/getUserName',                      
        success: function(data) {
            console.log('success');
            console.log(JSON.stringify(data));                               
        },
        error: function(error) {
            console.log("some error in fetching the notifications");
         }
    });
}

Node function

app.post('/getUserName',function(req,res){

        var reqData =  JSON.stringify(req.params);

        console.log("reqData :::: " + reqData);

    });

In the logs I can see

reqData :::: {}

Please suggest.

Upvotes: 0

Views: 2994

Answers (3)

Shubham Jain
Shubham Jain

Reputation: 930

You need to make use of body-parser middleware for extracting data from post request. You could do it this way:

var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
    extended: true
}));

app.post('/getUserName',function(req,res){

    var reqData =  JSON.stringify(req.body.data);

    console.log("reqData :::: " + reqData);

});

To extract data you need to get data as req.body.data and not req.params. This is used to get dynamic variables from your get route.

Upvotes: 0

Saurabh Jhunjhunwala
Saurabh Jhunjhunwala

Reputation: 2922

Finally found the answer I was not using app.use(bodyParser.urlencoded( { extended: false } )); because of which post was not working as expected.

Upvotes: 0

Srishan Supertramp
Srishan Supertramp

Reputation: 395

The POST data is received in req.body. req.params is used for dynamic parameters. For /users/:id, you'd get the value of id in req.params. Try using req.body for POST body data.

Upvotes: 1

Related Questions