3. Handling PUT Request
Index.js: Update code in the Index.js for PUT Request:
Index.js: Update code in the Index.js for PUT Request:
// PUT Request
app.put('/api/courses/:id', (req, res) => {
// look for the course
(Copy the code of app.get('/api/courses'))
// if not existing, return 404-resourse not found
const course = courses.find((c) => c.id === parseInt(req.params.id));
if (!course) res.status(404).send('Course with given id not found ');
res.send(course);
// validate (copy code from app.post('/api/courses'))
// if invalid, return 400 - bad request
const schema = {
name: Joi.string().min(3).required(),
};
const result = Joi.validate(req.body, schema);
if (result.error) {
res.status(400).send(result.error.details[0].message);
return;
}
// update course
// return update course to client
course.name = req.body.name;
res.send(course);
});
Output: To Execute PUT request, again we use POSTMAN tool with PUT request option.
4. Handling DELETE Request
Index.js: Update code in the Index.js for DELETE Request:
// Delete Request
app.delete('/api/courses/:id', (req, res) => {
// look for the course
(Copy the code of app.get('/api/courses'))
// if not existing, return 404-resourse not found
const course = courses.find((c) => c.id === parseInt(req.params.id));
if (!course) return res.status(404).send('Course with given id not found ');
res.send(course);
// delete course
const index = courses.indexOf(course);
courses.splice(index, 1);
// return deleted course to client
res.send(course);
});
Output: To Execute DELETE request, we use POSTMAN tool with DELETE
request option