I've looked through various posts and I'm feeling quite lost with this issue.
When I run console.log(req)
, the output is as follows:
ServerResponse {
...
req:
IncomingMessage {
...
url: '/my-endpoint',
method: 'POST',
statusCode: null,
statusMessage: null,
...
body: { foo: 'bar' },
_body: true,
...
route: Route { path: '/my-endpoint', stack: [Object], methods: [Object] } },
...
Everything seems fine, so naturally, I thought console.log(req.body)
would return { foo: 'bar' }
in the console...however, it returns undefined
After some investigation, I suspect there might be an issue in my app.js
file related to body-parser
, but I have already included all the necessary configurations
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var http = require('http');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
//Home Page Rendering
var index = require('./routes/index');
app.use('/', index);
// All other routes are kept in the `routes` module
require('./routes')(app);
module.exports = app;
routes.js
module.exports = function routing(app) {
var apiClient = require('./services/apiClient');
app.post('/get-device-info', function(err, req, res){
console.log("/get-device-info routes");
apiClient(req, res);
});
};
apiClient.js
module.exports = function callApi(req, res){
console.log(req);
console.log(req.body)
};
index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
Here's what I've attempted:
app.use(express.bodyParser());
Ensuring that the incoming request explicitly declares application/json
Trying different ways to declare body parser.json
Adding a config function