I am trying to use Controller here.
This is my app.js:
var express = require('express');
var app = express();
const routes = require('./Routes/route');
const bodyParser = require('body-parser');
app.use('/', routes);
// support parsing of application/json type post data
app.use(bodyParser.json());
//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({extended: true}));
var server = app.listen(8081);
This is my route.js:
const express = require('express');
const router = express.Router();
const controller = require('../Controllers/controller');
router.get('/counter', controller.showCount);
router.post('/addcount', controller.addCount);
module.exports = router;
This is my controller.js:
const db = require('../db-connect');
const showCount = (req, res) => {
if(db.state === 'disconnected'){
res.send('Server not connected');
}
else{
db.query('select * from Count', (err, rows, fields) => {
if (err) throw err
res.send(rows);
});
}
};
const addCount = (req, res) => {
console.log(typeof(req.body));
res.send(req.body);
}
module.exports = {showCount, addCount};
Problem: It seems like requests are not being parsed. Not sure why.
I am using post man to send request. I am sending data as 'form-data' by postman.
CodePudding user response:
you must add app.use('/', routes);
under the bodyParser middleware
// support parsing of application/json type post data
app.use(bodyParser.json());
//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({extended: true}));
app.use('/', routes);