NodeJS How to get server data sent from jQuery ajax call via POST

My client makes ajax call

{{ function callNode(){ console.log("I am called"); var data = {"emailId":" gopal@gmail.com "}; $.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 can get this request in my app.js application, but I can’t get the data that I pass. I tried to search, but nothing works.

 {{ 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); } } */ }} 

The thing is that it is not included in any request and response events (as I saw, many people use this to get data.

Help me find out what's wrong here, its first time ajax on node

+5
source share
3 answers

Since you are sending data as json, you need to change the contentType type relative to this, 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"); } }); 

Here you can see that the contentType is changed to application / json.

On the server side, you need to check request.body to get the data, not request.params.

+3
source

req.params does not do what you think.

 app.get('/:route', function(req, res) { console.log(req.params.route); }); 

A visit to /test will populate req.params.route with test .

You are looking for req.body that can only be used with body-parser middleware.

+1
source

You need to use the body-parser middleware ( https://www.npmjs.org/package/body-parser ) and you need to declare which badyParser to use

  • app.use (bodyParser.json ()) or
  • app.use (bodyParser.raw ()) or
  • app.use (bodyParser.text ()) or
  • app.use (bodyParser.urlencoded ())

    inside the main js file. Then the req.body object will contain your json / text / raw / urlencoded data.

+1
source

Source: https://habr.com/ru/post/1202320/


All Articles