My client is making an ajax call
{{
function callNode(){
console.log("I am called");
var data = {"emailId":"[email protected]"};
$.ajax({
type: 'POST',
data: JSON.stringify(data),
/* data: {
blob: {wob:"1",job:"2", ar:[1,2,{a:'b'}]}
},*/
contentType: "application/javascript",
//contentType: "application/x-www-form-urlencoded",
dataType:'json',
url: 'http://localhost:3000/notification',
success: function(data) {
console.log('success');
console.log(JSON.stringify(data));
},
error: function(error) {
console.log("some error in fetching the notifications");
}
});
}
}}
I am able to get this request in my app.js but not able to get the data that I am passing I tried to search but nothing is working
{{
app.post('/notification', function(req, res) {
JSON.stringify(req.params);
/*
var body;
req.on('data', function(chunk) {
console.log("Received body data:");
body += chunk;
});
// the end event tells you that you have entire body
/*req.on('end', function () {
try {
var data = JSON.parse(body);
colnosole.log(data);
} catch (er) {
// uh oh! bad json!
res.statusCode = 400;
return res.end('error: ' + er.message);
}
}
*/
}}
Thing is its not coming inside any events of request and response(as I have seen many people using this to fetch the data.
Help me to know whats wrong here its first time ajax on node
Since you sending data as json the contentType needs to be changed with respect to that so the ajax call should be:
$.ajax({
type: 'POST',
data: JSON.stringify(data),
/* data: {
blob: {wob:"1",job:"2", ar:[1,2,{a:'b'}]}
},*/
contentType: "application/json",
//contentType: "application/x-www-form-urlencoded",
dataType:'json',
url: 'http://localhost:3000/notification',
success: function(data) {
console.log('success');
console.log(JSON.stringify(data));
},
error: function(error) {
console.log("some error in fetching the notifications");
}
});
Over here you can see the contentType changed to application/json.
At the server end you need to check the request.body in order to get the data and not request.params.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With