@souvik88 can you help me please
I have problem in POST AND PUT please anyone check this for me
The JOI is returning error although I have given name: coursefour
also POST is not accepting my input of name: coursefour
if i remove the validation part of JOI, it only increases the value of ID
by 1 and not initilized the name
with
req.body.name
const Joi = require('joi');
const express = require('express');
const app = express();
app.use(express.json());
const courses = [
{ id: 1, name: 'bca' },
{ id: 2, name: 'bba' },
{ id: 3, name: 'mba' },
];
// PROBLEM IN POST
app.post('/api/courses', (req,res) => {
const { error } = validateCourse(req.body);
if (error) return res.status(400).send(error.details[0].message);
const course = {
id: courses.length + 1,
// PROBLEM IN POST
name: req.body.name
};
courses.push(course);
res.send(course);
});
// PROBLEM IN PUT
app.put('/api/courses/:id', (req,res) => {
const course = courses.find(c => c.id === parseInt(req.params.id));
if(!course) return res.status(404).send('The Course with given id not found');
const { error } = validateCourse(req.body); // result.error
if(error) return res.status(400).send(error.details[0].message);
course.name = req.body.name;
res.send(course);
});
function validateCourse(course) {
const schema = {
name: Joi.string().min(3).required()
};
return Joi.validate(course, schema);
}
const port = process.env.PORT || 8000;
app.listen(port, () => console.log(`Listening on port ${port}`));
POSTMAN SCREENSHOT