2

I have a simple server where i just prints a json to the screen when its posted. This is my code:

/*jslint node:true*/

var express = require('express');
var app = express();
app.use(express.json());
app.use(app.router);

app.post('/event', function (res, req) {
    //'use strict';
    console.log(req.body);
});

app.listen(3000);

Then i put a JSON to the server with curl:

curl -X POST -H "Content-Type: application/json" -d '{"username":"xyz","password":"xyz"}' http://localhost:3000/event

But the server just prints undefined

What am i doing wrong?

Naknut
  • 69
  • 1
  • 8

2 Answers2

5

you haven't defined usage of express.bodyParser()

it has to be done like this:

app.use(express.bodyParser());

live example: module routes file

exports.post = function(req, res){
    console.log(req.body);
    //res.render('index', { title: 'Express' });
};

application:

app.post('/post', routes.post);

fiddler request:

enter image description here

from comments: in case you have latest libs, you should take into account that bodyParser is deprecated from Connect 3.0. appropriate thread: How to get rid of Connect 3.0 deprecation alert?

Community
  • 1
  • 1
Eugene P.
  • 2,635
  • 17
  • 23
2

I just figured out what the problem is. It should be:

function (req, res)

and not:

function (res, req)

since the first parameter is the request and the second is the response.

Naknut
  • 69
  • 1
  • 8