1

I tried to move the routing from the Express App to another file, it works but when I try to get the body of the post request, it's undefined.

Here is the server.js file :

var winston = require('winston');
winston.remove(winston.transports.Console);
winston.add(winston.transports.Console, {colorize: true});
winston.add(winston.transports.File, { filename: 'server.err', level: 'error'});
winston.info('Starting server.');

var Firebase = require('firebase-admin');
var connection = require('./connection/firebaseConnection.json');

var express = require('express')
app = express();
var router = require('./srcs/router');
var bodyParser = require('body-parser');

try {
  Firebase.initializeApp({
    credential: Firebase.credential.cert({
      projectId: connection.firebase.project_id,
      clientEmail: connection.firebase.client_email,
      privateKey: connection.firebase.private_key
    }),
    databaseURL: 'https://' + connection.firebase.project_id + '.firebaseio.com'
  });
  winston.info('Connected to Firebase.');
} catch (error) {
  winston.error('Could not connect to Firebase : ' + error.code + ' : ' + error.message);
  process.exit(1);
}

app.use('/', router);

app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));

app.use(function(req, res, next) {
  var origin = req.headers.origin;
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'POST', 'GET');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type,X-Requested-With');
  res.setHeader('Access-Control-Allow-Credentials', true);
  return next();
});

var server = app.listen(80, function() {
  winston.info('Server listening on port 80.');
});

And here is the router.js

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

var winston = require('winston');

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

module.exports = router;

I did a curl on it using this command :

curl --data "title=test" http://localhost/post

And the router.post is triggered but the value is undefined.

3
  • 2
    Try adding the bodyParser middleware (the app.use call) before the router middleware call. Commented Jun 3, 2017 at 11:38
  • It worked, thanks ! Commented Jun 3, 2017 at 11:42
  • I have added an answer. Commented Jun 3, 2017 at 11:44

1 Answer 1

1

Try adding the bodyParser middleware (the app.use call) before the router middleware call.

The middlewares are run in the order in which they are added. You want the bodyParser to execute before reaching the router.

app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));

app.use('/', router);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.