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.
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.
Finally found the answer I was not using app.use(bodyParser.urlencoded( { extended: false } ));
because of which post was not working as expected.
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.
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.