i try to build a simple restapi, i still learning nodejs/expressjs here https://www.youtube.com/watch?v=f2EqECiTBL8
the problem is when i try to post data like this:
.post((req, res) => {
console.log('Received POST data:', req.body);
res.json({
"firstname": req.body.firstname,
"lastname": req.body.lastname
});
})
the req.body is an empty object.
When i replaced req.body.lastname with data.employees[1] that worked fine.
Here is the code:
const express = require('express');
const router = express.Router();
const data = {};
data.employees = require('../../data/employees.json');
router.route('/')
.get((req, res) => {
res.json(data.employees);
})
.post((req, res) => {
res.json({
"firstname": data.employees[0],
"lastname": data.employees[1]
});
})
module.exports = router;
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3500;
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
// Routing
app.use('/', require('./routes/root'));
app.use('/subdir', require('./routes/subdir'));
// set up api or rest api
app.use('/employees', require('./routes/api/employees'));
app.listen(PORT, () => console.log(`Server Running On Port ${PORT}`))
[
{
"id": 1,
"firstname": "Zaid",
"lastname": "El khobzi"
},
{
"id": 2,
"firstname": "Jhon",
"lastname": "Kennedy"
}
]
New contributor
Zayd is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.