drakoumelitos drakoumelitos - 5 months ago 16
Ajax Question

AJAX post to Express returns no data to req.query (yes there is the same q but nothing works)

this is my set up. However when I send data through the ajax the body is empty. On chrome under network I see the post and the content, with a correct payload:

request

{"EventName":"asd","PrivacyLevel":1,"TypeInt":1,"ExpectedDate":"asd","Desc":"asd","Down":0,"Up":0,"PostCode":"","Address":"","ID":""}


Most people say its the body parser, I have placed the parsers above the app.use(app.router) I dont know if it creates any conflict with express.json() but when I commented it out it didnt make any difference.

app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser('secret'));
app.use(express.session({ secret: 'randomstring' }));
app.use(express.bodyParser());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

$.ajax({
url: window.location.origin + '/registerEvent',
contentType: 'application/json: charset=utf-8',
dataType: 'json',
type: 'POST',
data: JSON.stringify(Event.toJSONString()),
cache: false,
timeout: 5000,
async: false,
success: function (result) {
success = true;
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('error ' + textStatus + " " + errorThrown);
success = false;
}
});

exports.registerEvent = function (req, res) {
if (req.session.lastPage === '/index' && req.xhr) {
console.log(req);
console.log(req.body);
console.log('body: ' + JSON.stringify(req.body));

var test = req.query.EventName;

Answer

The data will be available in req.body (the parsed HTTP request body from the AJAX JSON) not req.query (the URL query string).

In your jquery ajax code, use contentType: 'application/json' and that should get it doing the kind of POST request you want.