Reputation: 548
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.
Upvotes: 3
Views: 1096
Reputation: 806
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);
});
Upvotes: 0
Reputation: 111278
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.
Upvotes: 7