Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(data) {console.log(this)}
    });

and my express portion looks like this:

 var express = require('express');
 var app = express();
 var router = express.Router(); 

 app.set('port', (process.env.PORT || 5000));

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

this always outputs undefined in the console.

How can I change this around to make the req.body, or any part of the req, contain the information I am trying to send over to the express portion of the code.

like image 242
TwoShorts Avatar asked Dec 19 '25 13:12

TwoShorts


1 Answers

You need to use the body parser.

var bodyParser = require('body-parser')

app.use(bodyParser.json());

See:

  • https://github.com/expressjs/body-parser

You may also need to add:

contentType: 'application/json',

in your .ajax() options.

like image 56
rsp Avatar answered Dec 21 '25 02:12

rsp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!