Currently encountering an issue when attempting to log the body of a POST request in my console. Despite seeing the payload in my Chrome console with the correct data, I am receiving the following error:
express_1 | TypeError: Cannot read property 'exampleval' of undefined
This logic has worked for me without any problems in the past.
services/router.js
const express = require('express');
const http = require('http');
const bodyParser = require('body-parser');
var app = express();
// parse application/json
app.use(bodyParser.json());
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
const router = new express.Router();
const employees = require('../controllers/employees.js');
//router.route('/employees').post(employees.post);
router.post('/employees', function (req, res) {
var exampleval = req.body.exampleval;
console.log(exampleval);
})
module.exports = router;
services/web-server.js
const http = require('http');
const express = require('express');
const webServerConfig = require('../config/web-server.js');
const bodyParser = require('body-parser');
const router = require('./router.js');
const morgan = require('morgan');
const cors = require('cors');
let httpServer;
function initialize() {
return new Promise((resolve, reject) => {
const app = express();
httpServer = http.createServer(app);
// Combines logging info from request and response
app.use(morgan('combined'));
// enable cors on all routes
app.use(cors())
// Mount the router at /api so all its routes start with /api
app.use('/api', router);
// Body Parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
httpServer.listen(webServerConfig.port)
.on('listening', () => {
console.log(`Web server listening on localhost:${webServerConfig.port}`);
resolve();
})
.on('error', err => {
reject(err);
});
});
}
module.exports.initialize = initialize;
function close() {
return new Promise((resolve, reject) => {
httpServer.close((err) => {
if (err) {
reject(err);
return;
}
resolve();
});
});
}
module.exports.close = close;
I believe these are the only essential sections of code. Any guidance on how to resolve this issue would be highly appreciated as my goal is to eventually utilize these values in an SQL query.