0

I've created a very basic express js application. After setting routes and other things I did app.use('/api/', require('./api/api.js'));

api.js looks something like this:

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

router.post('/', function(req, res){
      res.end(req.body);
});

module.exports = router;

I'm using Postman chrome extension to post to this route. The response is empty {}.

The question is: as long as I have in my app.js body-parser middleware set do I need to set it again in api.js ? If not why I have an empty response ?

In app.js body-parser is set like this:

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
        extended: false
}));
Tarida George
  • 1,303
  • 3
  • 17
  • 36

2 Answers2

1

Try this

app.js

var express = require('express');
var app = express();
var bodyParser = require('body-parser');

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded

var api = require('./api');
app.use('/api', api);


var server = app.listen(3000, function () {

  var host = server.address().address;
  var port = server.address().port;

  console.log('Example app listening at http://%s:%s', host, port);
});

api.js

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

router.post('/', function (req, res) {
  res.send((req.body);
});

module.exports = router

Then, in your PostMan request, something like:

enter image description here

Alex
  • 37,502
  • 51
  • 204
  • 332
  • if I do something like this `res.send("something");` I can see the response in postman. The problem is with the body-parser. `"express": "^4.12.3"`, `"body-parser": "^1.12.2"` – Tarida George Apr 17 '15 at 08:28
  • hmm.. i suspect it's something to do with your request in Postman - could you try and post a screenshot to your main question? – Alex Apr 17 '15 at 08:34
  • which version of express are you using? – Alex Apr 17 '15 at 08:39
  • @George02 see my edit - notice var bodyParser = require('body-parser'); - and then see screnshot of my PostMan request. be sure to set content type to application/json – Alex Apr 17 '15 at 08:42
  • I took your example, I did `npm install express body-parser --save` and it won't work. I tested with another REST client(chrome extension). The data that I send to server need to be in the header or in the `payload` ? – Tarida George Apr 17 '15 at 09:17
  • the response is empty `{}` `req.body` is not filled by body-parser and I don't know why. – Tarida George Apr 17 '15 at 09:21
  • 1
    Doing what @sirthud says here http://stackoverflow.com/questions/24543847/req-body-empty-on-posts work. Posting in raw format. – Tarida George Apr 17 '15 at 09:29
0

You used /api/ in app.use('/api/', require('./api/api.js')); to use the route and in route you used router.post('/', .... If you remove the trailing forward slash in /api/ it might work.

A Yashwanth
  • 318
  • 4
  • 12