Last Sync: 2022-08-04 14:00:04

This commit is contained in:
tactonbishop 2022-08-04 14:00:04 +01:00
parent 948523b0ca
commit 491cb388b4
2 changed files with 69 additions and 0 deletions

View file

@ -66,6 +66,17 @@ app.get("/api/courses/:id", (req, res) => {
We use the `:` symbol in the URI to indicate that we looking to parse for a specific value in the data. Now if we call `/api/courses/2`, we will get the second item in the array. We use the `:` symbol in the URI to indicate that we looking to parse for a specific value in the data. Now if we call `/api/courses/2`, we will get the second item in the array.
The block above is the most basic format but we would want to add some kind of error handling, for example:
```js
app.get("/api/courses/:id", (req, res) => {
const course = courses.find((c) => c.id === parseInt(req.params.id));
if (!course) res.status(404).send("A course with the given ID was not found");
res.send(course);
});
```
## Queries ## Queries
Whereas parameters return specific data points, queries don't get data they aggregate or present the data that is returned in a certain way, such as for instance applying a search function. We indicate queries with a `?` in our URI. Whereas parameters return specific data points, queries don't get data they aggregate or present the data that is returned in a certain way, such as for instance applying a search function. We indicate queries with a `?` in our URI.

View file

@ -0,0 +1,58 @@
---
tags:
- Programming_Languages
- backend
- node-js
- express
- REST
- apis
---
# Creating a REST API with Node and Express: POST requests
To demonstrate the handling of POST requests, we will create a handler that add a new element to the array of courses.
```js
app.post('/api/courses', (req, res) => {
const course = {
id: courses.length + 1,
name: req.body.name
}
courses.push(course);
res.send(course)
})
```
Here we use the body that is sent from the client and isolate the field `name`. This presupposes that the client is sending us data with the following shape as the body:
```json
{
"name": "Biology and Life Sciences"
}
```
To execute the PUT request from the frontend:
```js
const addCourse = async (newCourse) => {
try {
const resp = await axios.post("http://localhost:3000/api/courses", {
name: newCourse,
});
console.log(resp.data);
} catch (err) {
console.error(err);
}
};
addCourse("Biology and Life Sciences");
```
Which returns:
```js
{ id: 4, name: 'Biology and Life Sciences' }
```
The `id` is added by the server, not the client. Having created the new value we add it to our `courses` array. (In reality we would be creating a new entry in a database.) Then we follow the convention of returning the new value back to the client.