Issue
I’m currently learning about creating a server using the node.js framework Express.
Using the code below I understand how to access or GET the list of students or GET 1 student by name, however I’m not sure how to DELETE a student by id. I tried the localhost:4000/students/1 and it doesn’t work, what should the URL it look like?
Same questions for the app.put method. If I type localhost:4000/students/James/art/50 I simply get an error saying "cannot get localhost:4000/students/James/art/50" so it never actually uses the put method.
const express = require('express');
const bodyParser = require('body-parser');
app.use(bodyParser.json());
let students = [
{
id: 1,
name: 'James',
classes: {
computer: 95,
art: 92
}
},
{
id: 2,
name: 'Leeroy',
classes: {
computer: 95,
art: 92
}
}
];
app.get('/students', (req, res) => {
res.json(students);
});
app.get('/students/:name', (req, res) => {
res.json(students.find((student) => student.name === req.params.name));
});
app.put('/students/:name/:class/:grade', (req, res) => {
const student = students.find((student) => student.name === req.params.name);
if (student) {
student.classes[req.params.class] = parseInt(req.params.grade);
res.status(201).send(`Student ${req.params.name} was assigned a grade of ${req.params.grade} in ${req.params.class}`);
} else {
res.status(404).send('Student not foun');
}
});
app.delete('/students/:id', (req, res) => {
const student = students.find((student) => student.id === req.params.id);
if (student) {
students = students.filter((obj) => obj.id !== req.params.id);
res.status(201).send('Student was deleted.');
}
});
app.listen(4000, () => {
console.log('Your app is listening on port 4000');
});
Solution
You’ll need to use a tool in order to test requests different to GET, I recommend Postman there you’ll be able to test the DELETE, PUT and POST requests