I have nearly completed the first instance of the CRUD-app course, but can’t get past the final stages of validating the POST and DELETE functions.
As far as my humble eyes can see, my code is pretty close to the one Mosh provided for the Vidly app in the next lesson of the course. But I keep getting error messages when sending requests from postman.
Have I done anything wrong? Or is it an update issue with the packages, is there a way around these error?
Here the responses in Postman:
|POST |http://localhost:3000/api/courses/n
// gives 404. Not found. message: Cannot POST /api/courses/n
|DELETE|http://localhost:3000/api/courses/n
// gives 404. Not found. Message Cannot DELETE /api/courses/n
(n as any number)
My code:
const Joi = require(‘joi’);
const express = require(‘express’);
const app = express();
app.use(express.json());
const courses = [
{ id:1, name: 'course1' },
{ id:2, name: 'course2' },
{ id:3, name: 'course3' },
];
app.get('/api/courses', (req, res) => {
res.send(courses);
});
app.post("/api/courses", (req, res) => {
const name = { name: req.body.name };
const schema = Joi.object({ name: Joi.string().min(3).required() });
const result = schema.validate(name);
if (result.error) {
res.status(400).send(result.error.details[0].message);
}
courses.push(course);
res.send(course);
});
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 the given ID was not found.');
const { error } = validateCourse(req.body);
if (error) return res.status(400).send(error.details[0].message); // 400 message -
course.name = req.body.name; // Update course
res.send(course); // Return the updated course
});
// DELETE Request
app.delete('/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 the given ID was not found.'); //404
// Delete
const index = courses.indexOf(course);
course.splice(index, 1);
res.send(course);
});
//api/courses/1
app.get('/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 the given ID was not found.'); //404
res.send(course);
});
function validateCourse(course){
const schema = {
name: Joi.string().min(3).required()
};
return Joi.validate(course, schema); //validate
}
// PORT
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on port ${port}...`));