eolas/zk/3_PUT.md

50 lines
1,023 B
Markdown
Raw Normal View History

2022-08-04 14:30:04 +01:00
---
2022-08-28 10:37:22 +01:00
tags: [backend, node-js, REST, APIs]
2022-08-04 14:30:04 +01:00
---
2022-08-30 10:00:04 +01:00
# Creating a RESTful API: `PUT` requests
2022-08-04 14:30:04 +01:00
To demonstrate the handling of PUT requests, we will create a handler that
updates an element in the course array, based on its `id` and return the updated
entry:
2022-08-04 14:30:04 +01:00
```js
2022-08-30 10:00:04 +01:00
router.put("/:id", (req, res) => {
2022-08-04 14:30:04 +01:00
const course = courses.find((c) => c.id === parseInt(req.params.id));
2022-08-30 10:00:04 +01:00
if (!course)
return res.status(404).send("A course with the given ID was not found");
2022-08-30 14:30:05 +01:00
2022-08-30 10:00:04 +01:00
const { error } = validateCourse(req.body);
2022-08-04 14:30:04 +01:00
2022-08-30 10:00:04 +01:00
if (error)
return error.details.map((joiErr) => res.status(400).send(joiErr.message));
2022-08-04 14:30:04 +01:00
course.name = req.body.name;
res.send(course);
});
```
2022-08-28 10:37:22 +01:00
2022-08-04 14:30:04 +01:00
Our request:
```js
const updateCourse = async (courseChange) => {
try {
2022-08-30 10:00:04 +01:00
const resp = await axios.put("http://localhost:3000/api/courses/1", {
2022-08-04 14:30:04 +01:00
name: courseChange.name,
});
console.log(resp.data);
} catch (err) {
console.error(err);
}
};
2022-08-30 10:00:04 +01:00
updateCourse({ name: "A new course" });
2022-08-04 14:30:04 +01:00
```
Returns:
```js
2022-08-04 15:00:04 +01:00
{ id: 1, name: 'A new course' }
2022-08-28 10:37:22 +01:00
```