| Semester_4 |
|---|
| 01_Introduction |
| 02_DeployAzure |
| 03_JSBasic |
| 04_OOP |
| 05_GET |
| 06_POST |
| 07_PUT |
| 08_PATCH |
| 09_DELETE |
| 10_FrontendTable |
| 11_FrontendAdd |
| 12_FrontendDelete |
| 13_FrontendEdit |
| 14_Database |
In REST, PUT is one of the main HTTP methods — just like GET, POST, PATCH, and DELETE.
Each method describes what kind of action the client wants the server to perform.
| Method | Action | Description |
|---|---|---|
| GET | Read | Retrieve data |
| POST | Create | Add new data |
| PUT | Replace | Update an existing resource completely |
| PATCH | Modify | Update part of an existing resource |
| DELETE | Remove | Delete a resource |
PUT is used to update or replace an existing record with new data.
The client sends a PUT request to
/api/students/1.
The server finds the student with ID = 1.
The server replaces that student’s data with the new data.
The server returns the updated student object as JSON.
// **NEW** replaces the student's data
app.put("/students/:id", (req, res) => {
const id = parseInt(req.params.id);
const { name, course } = req.body;
if (!name || !course) {
return res.status(400).json({ error: "Name and course are required!" });
}
// Returns the index of the student with the id.
const pos = students.findIndex(s => s.id === id);
if (pos === -1) {
return res.status(404).json({ error: "Student not found" });
}
// update an existing student; replace the object
students[pos] = { id, name, course };
res.json(students[pos]);
});const pos = students.findIndex(s => s.id === id);
Returns the index of the student with the
id.
.find()→ “Give me the student.”
.findIndex()→ “Tell me where that student is in the array.”
Part Meaning studentsAn array of student objects — for example: [{ id: 1, name: "Anna" }, { id: 2, name: "Ben" }].findIndex()A JavaScript array method that searches the array and returns the index (position) of the first element that matches a condition. s => s.id === idAn arrow function that defines the search condition — here, it checks if a student’s idequals the givenidvariable.const pos = ...Saves the found index number into the variable pos.
students[pos] = { id, name, course };
That line is a key part of how you update an existing object (like a student) inside an array in JavaScript.
Part Meaning studentsAn array that holds all the student objects. Example: [{ id: 1, name: "Anna" }, { id: 2, name: "Ben" }]posThe index (position) in the array of the student you want to update. Usually found using .findIndex().=The assignment operator, which replaces the existing item at that position. { id, name, course }A new object containing the updated student data. This uses object shorthand, so it’s the same as { id: id, name: name, course: course }.
Local:
curl -X PUT http://localhost:3000/students/3 \
-H "Content-Type: application/json" \
-d '{"name":"Clara Becker","course":"Data Science"}'
Do not forget.
Deploy and test.