Skip to content Skip to sidebar Skip to footer

Express Keeps Getting Request.body As Undefined Json Object

I am making an Ajax request that looks like this: $.ajax({ url: '/gen', type: 'POST', data: JSON.stringify({'one': 1, 'two':2}), success: function(

Solution 1:

You need to use the body parser.

var bodyParser = require('body-parser')

app.use(bodyParser.json());

See:

You may also need to add:

contentType:'application/json',

in your .ajax() options.

Solution 2:

To use use req.body you have to use the bodyParser middleware, import it like this:

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

router.post('/gen', function(req, res) {
     console.log(req.body);
 });

Post a Comment for "Express Keeps Getting Request.body As Undefined Json Object"