Node.js how to read json data from request?

I have a server:

app.post('/', function(req, res, next) { console.log(req); res.json({ message: 'pppppppppppppssssssssssssss ' }); }); 

The request is sent from the client as:

 $.ajax({ type: "POST", url: self.serverURI, data: JSON.stringify({ "a": "128", "b": "7" }), dataType: 'json', success: function (result) { console.log(result); }, error: function (xhr, ajaxOptions, thrownError) { console.log(xhr); } }); 

while the connection is perfect.

My problem on the server:

 console.log(req); 

where I want to read the data that I sent. How to read { "a": "128", "b": "7" } from req ?

+6
source share
1 answer

Although you are not mentioning this, your code looks like it was written for the Express environment. My answer is aimed at that.

Be sure to use body-parser for Express. In case your project depends on some generated template code, it is most likely already included in your main script server. If not:

 var bodyParser = require('body-parser'); app.use(bodyParser.json()); 

Installing with npm: npm install body-parser --save

After that, the parsed JSON can be obtained through req.body :

 app.post('/', function(req, res, next) { console.log(req.body); // not a string, but your parsed JSON data console.log(req.body.a); // etc. // ... }); 
+4
source

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


All Articles