Express JS #5 - Post Requests

Anson the Developer
12 Feb 202413:18

Summary

TLDRThis tutorial explains how to create a resource on a backend server using a POST request in Express. It walks through setting up an API to accept user data from the frontend, such as username, password, and email, and saving it to a database or file. The video also demonstrates how to use Thunder Client in VS Code for testing POST requests. It introduces Express middleware to parse JSON request bodies and how to handle response statuses, including returning the created user data and status codes like 201. The tutorial ends by simulating user ID generation in the absence of a database.

Takeaways

  • πŸ“ You can create data on the backend using POST requests, which typically saves data to a database or a file.
  • 🌐 When a user fills out a form on the frontend (like a signup form), a POST request is made to the backend when the form is submitted.
  • πŸ“¦ The data sent from the frontend to the backend during a POST request is known as a 'request body' or 'payload'.
  • πŸ”„ The backend processes the request, validates the data, and saves it before responding with a status code (usually 201 for created resources).
  • πŸš€ To make POST requests, you need an HTTP client tool such as Postman, Hopscotch, or the VS Code extension Thunder Client.
  • βš™οΈ Thunder Client is an integrated REST API tool in VS Code that allows developers to make API requests directly from the IDE.
  • πŸ”§ Express, by default, doesn't parse JSON in the request body, so you need to use middleware like `express.json()` to handle JSON data.
  • πŸ‘¨β€πŸ’» Once the request body is properly parsed, you can perform operations like adding new users by pushing the data to an array.
  • πŸ”„ To simulate auto-incrementing IDs in the absence of a database, the example uses the last array element's ID and increments it by one.
  • πŸ“‘ After processing a POST request, the server should return a status code 201 to indicate successful resource creation.

Q & A

  • What is a POST request in the context of an API?

    -A POST request is used to send data to the server to create a new resource, such as submitting a form to register a user, and it includes a request body or payload.

  • What is the purpose of a request body in a POST request?

    -The request body, also known as payload, contains the data being sent from the client to the server. In a POST request, the request body includes information like user details (username, password, etc.) that the server will process.

  • Why is it important to use middleware when handling POST requests in Express?

    -Middleware is important for parsing incoming request bodies in Express. For example, the `express.json()` middleware is needed to parse JSON data sent in the POST request, as Express does not handle this automatically.

  • What is the significance of the 201 status code in a POST request?

    -A 201 status code indicates that a new resource has been successfully created. It is typically returned after a successful POST request.

  • What tool is introduced to test API requests within VS Code?

    -The tool introduced for testing API requests within VS Code is Thunder Client. It is a lightweight REST API client that allows you to make HTTP requests directly from VS Code.

  • Why does the console log β€˜undefined’ when sending data in a POST request initially?

    -The console logs β€˜undefined’ because Express is not automatically parsing the JSON data from the request body. This issue is resolved by using the `express.json()` middleware.

  • How can the same URL path be used for both GET and POST requests in Express?

    -The same URL path can be used for both GET and POST requests because the HTTP method (GET or POST) determines how the server will handle the request, even if the path is identical.

  • What happens if you send a POST request without a database to store data?

    -Without a database, you can simulate storing data by using an array in memory. In the example, new users are added to a mock array, and the array is updated with each POST request.

  • How does the example in the script generate a unique ID for each new user without a database?

    -The example generates a unique ID by taking the ID of the last user in the array, incrementing it by 1, and assigning it to the new user.

  • What is the role of the spread operator in the new user creation process?

    -The spread operator is used to unpack all the fields from the request body and include them in the new user object being created, making it easier to handle multiple fields.

Outlines

00:00

πŸ“¨ Introduction to Post Requests and Request Body

This section introduces how to create data on the backend using a post request. It explains the process of sending a form from the client side (like a signup form with username, password, email, etc.) to the backend through an API, which can be any type of server, not just Express. The request body or payload is the data being sent, and the backend validates, processes, and stores this data, typically returning a 201 status code upon successful creation. The speaker also discusses the need for an HTTP client to send request bodies since browsers don't allow it directly.

05:00

πŸ”¨ Setting Up Thunder Client for API Requests

This part focuses on setting up the Thunder Client in VS Code to test HTTP requests. Thunder Client is a lightweight REST API tool that allows users to make get, post, and other requests directly from VS Code. The speaker walks through installing the Thunder Client extension, setting up a simple get request to an Express API, and explains how Thunder Client functions similarly to Postman.

10:03

πŸ“© Creating a Post Request in Express

Here, the speaker describes how to create a post request in an Express API. The post request is defined on the same route as the get request (`/api/users`), but since they use different HTTP methods, there's no conflict. They walk through setting up the post route, sending a request with Thunder Client, and handling the request body. At this point, the body is undefined because Express doesn't automatically parse incoming request bodies, which requires adding middleware.

βš™οΈ Adding Middleware to Parse JSON

In this section, the speaker explains how to use middleware in Express to parse JSON request bodies. By adding `express.json()` as middleware, the server can now parse JSON data coming from the client. After updating the code, the speaker demonstrates how Thunder Client successfully sends data that the Express server can now read, and logs the received request body in the console.

πŸ“Š Adding New Users Without a Database

This part covers how to handle and store the data received from the post request. The speaker explains how to add a new user to a mock array by creating a unique ID based on the last element in the array. They demonstrate destructuring the request body, adding the new user to the mock array, and returning a response with a 201 status code to indicate successful creation. The speaker emphasizes good practice by using the correct status code.

Mindmap

Keywords

πŸ’‘GET Request

A GET request is an HTTP method used to retrieve data from a server. In the video, the speaker mentions how the client-side (browser) has been using GET requests to fetch data from the Express API, such as making a request to 'localhost:3000/API/users' to retrieve user information. It forms the foundation for understanding other request methods like POST.

πŸ’‘POST Request

A POST request is another HTTP method used to send data to a server, usually to create a new resource, such as adding a user to a database. In the video, the speaker explains how the client-side (e.g., a signup form) sends user data through a POST request to create a new user on the backend server, which saves this data in a database or file.

πŸ’‘Request Body

The request body refers to the data sent by the client in a POST request. This payload, typically in JSON format, contains the information needed to create or update a resource. In the example from the video, the speaker describes sending user information (username, password, email) as a request body when a user submits a signup form.

πŸ’‘Express API

Express API refers to a backend framework in Node.js used to build web applications and APIs. In the video, the Express API handles HTTP requests like GET and POST. The speaker shows how to set up routes such as '/API/users' for processing user-related requests and explains how the backend processes and responds to requests.

πŸ’‘Middleware

Middleware in Express is a function that processes requests before the server responds. In the video, the speaker introduces middleware to parse JSON request bodies, allowing the server to read and interpret incoming data properly. This middleware must be registered using `app.use(Express.json())` to ensure POST request bodies are parsed correctly.

πŸ’‘Thunder Client

Thunder Client is an API testing tool integrated with VS Code that allows developers to make HTTP requests directly from the editor. In the video, the speaker uses Thunder Client to send GET and POST requests to the Express server, providing a convenient alternative to tools like Postman or Hopscotch.

πŸ’‘JSON

JSON (JavaScript Object Notation) is a lightweight data-interchange format used to send and receive structured data between a client and server. The video demonstrates how data is sent to the server in JSON format when creating a new user, and how Express middleware is used to parse the incoming JSON request body.

πŸ’‘Status Code

HTTP status codes are returned by the server to indicate the outcome of a request. In the video, the speaker highlights the significance of status codes, particularly '201' for successful POST requests, signaling that a new resource (e.g., a user) has been created, and '200' for successful GET requests.

πŸ’‘API Route

An API route is a URL pattern that defines how the server responds to client requests. In the video, the speaker demonstrates creating two routes with the same path, '/API/users,' but handling different HTTP methods: one for GET requests to retrieve users and another for POST requests to create a new user.

πŸ’‘Array

An array is a data structure used to store multiple values in a single variable. In the video, the speaker uses an array (`mockUsers`) to simulate a database of users. When a new user is created via a POST request, the new user object is added to the array, and the array is updated with an incremented ID.

Highlights

Introduction to creating data using a POST request in Express API.

Explains how the client-side form sends user data (username, password, email) via a POST request to the backend.

Definition of 'request body' or 'payload'β€”the data sent from the client to the backend in a POST request.

The backend performs validation, parsing, and other necessary operations before saving the data.

Introduction to HTTP clients (Postman, Hopscotch, Thunder Client) used to make API requests beyond simple GET requests.

Setup of Thunder Client, an API testing tool in VS Code, as an alternative to Postman.

Demonstrates switching between GET and POST requests using Thunder Client, with a sample POST request to create a user.

Mentions how Express API differentiates between GET and POST requests on the same route.

Logs request body data to the console to verify data transmission from client to server.

Explanation of why the request body is undefined and how Express doesn't parse incoming JSON data by default.

Introduces the concept of middleware in Express, specifically for parsing JSON data using `express.json()`.

Details how to implement middleware in Express to parse JSON request bodies before handling API requests.

Shows how to create a new user object with a unique ID and push it to a mock array, simulating database behavior.

Uses the spread operator to unpack fields from the request body into the new user object.

Demonstrates the use of status codes, particularly the 201 status code, to indicate successful resource creation in a POST request.

Transcripts

play00:04

now that you all know how to retrieve

play00:06

data from the express API using get

play00:09

requests I'm going to show you how you

play00:11

can create data using what is called a

play00:14

post

play00:15

request now let's say for example you

play00:17

want to create a resource on the backend

play00:21

and that backend will save it to a

play00:22

database or save it to a file or save it

play00:25

just somewhere doesn't matter where it

play00:27

is you want to create let's say a user

play00:29

so your client your front end

play00:31

application will have a user form they

play00:33

fill out their username password email

play00:35

and other additional Fields once they

play00:37

are ready they will click that sign up

play00:39

button when you click that sign up

play00:41

button it will make an API request to

play00:45

the backend doesn't have to be

play00:47

necessarily an Express API server it can

play00:49

be really any API server that's running

play00:51

that handles that post request okay so

play00:54

the front end the client side would make

play00:56

an HTTP request a post request to the

play01:00

server okay once the server receives

play01:04

that request the server needs to

play01:06

obviously be able to grab the data that

play01:07

we're trying to send from the client

play01:09

side to the back end and that data that

play01:12

you're sending is known as a request

play01:15

body so whenever you make post requests

play01:18

the data that you want to send to the

play01:20

backend server you send it via a payload

play01:23

or a request body you use those terms

play01:26

synonymously so payload request body are

play01:28

interchangeable terms the backend will

play01:31

then take that data and it will perform

play01:34

the necessary operations in need so

play01:36

typically validation if it need to do

play01:38

additional parsing if it needs to make

play01:39

sure that it has the proper Fields it

play01:42

will do all that stuff before it can

play01:44

proceed with either saving it to a

play01:46

database or saving it to some external

play01:48

API Source whatever it is I need to do

play01:51

once it's done saving that record to the

play01:54

database or somewhere it will return a

play01:57

2011 response which or 2011 status code

play02:01

which typically just means that the

play02:02

resource was created sometimes it might

play02:04

also return the new record that was

play02:07

created so that way if you need to use

play02:09

it on the client side for whatever

play02:10

reason you can do so now before we

play02:13

actually can make any post requests we

play02:16

do need an HTTP client to actually uh

play02:19

make those requests and also be able to

play02:21

send a request body to our Express API

play02:25

because on the browser there's no

play02:26

built-in tool that enables you to send

play02:29

requests bodies unless if you to write

play02:32

the code in the JavaScript console but

play02:33

we're not going to do that um so there

play02:35

are different uh clients that you can

play02:37

use to interact with your API So

play02:40

currently we've just been using the

play02:41

browser which we limited to just making

play02:44

get requests by simply typing in the

play02:46

address in the address bar we want to be

play02:49

able to make post requests where we can

play02:50

send actual data okay so you can use

play02:54

tools like Postman there's also

play02:56

Hopscotch which is an alternative to

play02:58

postman for for this tutorial I'm going

play03:00

to keep things simple I'm going to keep

play03:02

everything inside vs code and we're

play03:04

going to install this extension so on

play03:06

the left hand side or um wherever you

play03:08

have this extensions icon just click on

play03:11

extensions and you want to search for an

play03:14

extension called Thunder

play03:16

client and thunder client is a very

play03:19

lightweight rest API tool for VSS code

play03:22

it's integrated in there you just have

play03:24

to install it and it allows you to make

play03:27

API calls to your Express server

play03:30

so I'll go ahead and click

play03:32

install Okay and then I'm going to go

play03:35

just close

play03:36

this and then let's go ahead on the left

play03:39

hand side you should see the Thunder

play03:40

client appear right over here as an icon

play03:44

that's the Thunder client and I'll click

play03:46

on it and

play03:48

now what I can do is I can create a new

play03:52

request by clicking on the new request

play03:55

button and you can see now it looks it

play03:58

it looks kind of identical to to postman

play04:01

if you've used it before or really any

play04:03

other rest client but we have an address

play04:06

bar where we can uh type in the address

play04:09

or the URL that we want to make requests

play04:12

to so I'll type in Local Host Port

play04:14

3000 / API users I'll make a get request

play04:19

so I can select this drop down and

play04:20

select get and I'll click Send and you

play04:22

can see that it gives us back the

play04:24

data just like that okay and we're going

play04:28

to use this client to switch between

play04:31

different types of HTTP requests that we

play04:34

want to make so we'll switch from get to

play04:36

post and then in later videos when I

play04:38

show you how to handle put requests or

play04:39

delete requests we will switch to these

play04:42

HTTP requests as well okay so let's

play04:46

close this out just wanted to show you

play04:48

all how to set up thunder client so now

play04:51

what I'm going to do is set up our post

play04:52

request to be able to create a brand new

play04:55

user so what I'm going to do is right

play04:58

underneath my

play05:00

uh API users route I'll go ahead and

play05:04

reference the app variable and since I

play05:07

want to register a post request I'm

play05:09

going to go ahead and call the Post

play05:11

method so this method is very similar to

play05:14

all the other HTTP verb methods such as

play05:17

get put delete uh it takes in a path so

play05:22

over here I'm going to go and pass

play05:24

inapi users now you're probably

play05:27

wondering well should we be able to

play05:29

reuse the path and the answer is yes

play05:32

because you have a different HTTP

play05:35

request type being used so this is for

play05:37

post request and the one over here is

play05:40

for get requests okay when your HTTP

play05:43

client is making requests the server

play05:46

knows if it's making a get or a post

play05:48

request so that way there's no

play05:50

confliction between these two different

play05:52

types of requests despite the route

play05:55

being the same so we'll also pass in in

play05:59

a request and

play06:01

response or we'll pass in the request

play06:03

Handler function which will have these

play06:05

two arguments request and response and

play06:08

then for now I will just return a

play06:10

response. send I'll just pass in a 200

play06:14

status code or I'll just pass in 200 and

play06:18

I'll just console log the request body

play06:22

just so that we can see what our data is

play06:24

looking like when we send it from the

play06:26

client so let's go back to thunder

play06:28

client so I'll click on the Thunder icon

play06:30

I'll click on new request and up top

play06:33

where you see gets just click on that

play06:35

drop down and select post and we're

play06:38

going to change the url and we're going

play06:41

to type in Local Host Port 3000 API

play06:45

users okay so once again we have uh we

play06:49

have two different types of

play06:51

HTTP uh methods but they both use the

play06:54

same path okay so whenever I call a post

play07:00

request to API users I don't even need

play07:03

to send any data for now it's just going

play07:04

to give me back a 200 status

play07:08

code now I can go into the body tab in

play07:11

my thunder client and I can select Json

play07:15

if I want to send Json so if I try to

play07:18

send a request body let's see what

play07:19

happens let's click Send so in the

play07:22

console log for our in our terminal you

play07:25

can see that right now it's actually

play07:27

logging undefined on I try to send it

play07:30

again it still logs undefined and you're

play07:31

probably wondering well what's going on

play07:32

with this why is it undefined well the

play07:34

reason why it's undefined is because

play07:36

right now by default Express is not

play07:38

parsing those request bodies that are

play07:41

coming in so whenever I am sending Json

play07:44

to the express server the headers set

play07:47

the content type to application Json

play07:50

Express doesn't parse those payloads by

play07:53

default so we need to tell Express to do

play07:54

so now this is going to require us to

play07:57

use a middleware so this is kind of like

play07:58

a brief little intro to middlewares but

play08:00

don't worry so much about it once we

play08:02

actually get into the topic of

play08:03

middlewares you'll better understand how

play08:05

they work but all of middleware is is

play08:07

just a function that is going to be

play08:08

invoked before uh certain API requests

play08:12

are being handled so in my case I want

play08:15

to make sure that right before my post

play08:18

request is being received I want to make

play08:20

sure that that middleware that parses

play08:22

the Json payload accordingly is being

play08:26

invoked so you typically want to

play08:28

register your middleware as early as

play08:30

possible so the best way to do it is

play08:31

doing it up top after you create your

play08:34

Express app instance so I'm going to go

play08:37

ahead and reference app and I'm going to

play08:39

call the use method and this is the

play08:41

method that you use to register

play08:44

middleware and the middleware that we're

play08:46

going to register is actually already

play08:48

built into Express so I can just

play08:51

reference Express and call this

play08:54

Json

play08:55

method okay so now you can even read

play08:58

over here it looks at requests where the

play09:00

content type header matches the type

play09:02

option so in this case this is express.

play09:04

Json there's also other um uh there's

play09:08

also other things that you can uh parse

play09:10

to like let's say if you're trying to

play09:11

send text or if you're trying to send uh

play09:14

URL encoded or raw data so hopefully

play09:18

that makes sense so in our case we'll

play09:20

keep it as

play09:22

Json and let's go ahead and see what

play09:23

happens if I send the request

play09:26

again so let's go back into

play09:30

our ther client I'll click

play09:32

Send I'll just click it again and now

play09:35

watch this you can see that in the

play09:38

console it is logging that

play09:41

request that that request body that I am

play09:44

sending to the express server and I can

play09:47

literally add as many fields as I want I

play09:49

can add a display

play09:51

name let's do Anson

play09:54

the dev click Send again and you can see

play09:58

that it is is being logged right over

play10:00

here okay perfect all right

play10:02

cool now let's go ahead and actually do

play10:05

something with the data so like I said

play10:07

right now we don't have an actual

play10:09

database so all I'm going to do is just

play10:12

push this user to the array

play10:15

so uh to do that what we'll do is we'll

play10:18

assume that the request body is valid

play10:20

but then in the next section I'm going

play10:22

to show you how we can actually validate

play10:25

the request body so I'm going to go

play10:27

ahead and create a variable called new

play10:29

user equals so we need to actually grab

play10:33

all of the fields from the request body

play10:36

but we also need to attach an ID to the

play10:39

request body and once again since we

play10:41

don't have a database to manage our uh

play10:44

IDs because typically the database is

play10:46

responsible for generating those

play10:49

IDs all I'm going to do is just take uh

play10:53

the last element the last user in the

play10:55

mock user array uh take the ID of that

play10:58

last user add one to it and assign that

play11:00

to the new user the new new user's ID

play11:04

okay so what I'll do is I'll first do

play11:09

this mock users so I'm just going to

play11:10

reference mock users um and then I'm

play11:13

going to want to get the last element so

play11:16

mock users. length minus

play11:19

one okay so the length of our array is

play11:22

going to be 7 and I want to reference

play11:24

the last element so that's going to be

play11:26

at index 6 because remember arrays are

play11:28

indexed at

play11:29

Aras are zero and next and then we're

play11:32

going to reference ID and just add one I

play11:34

know this is kind of like a hacky way to

play11:35

do it but I just want I'm just doing it

play11:36

just for a very simple example and then

play11:40

what I'll do is I'm just going to

play11:43

sign uh or I'm going to destructure the

play11:46

request

play11:47

body so I'm going to destructure body

play11:49

from the request object and then I'll

play11:51

just simply use the spreader operator on

play11:55

the body object to take all of the

play11:57

fields from the body object and unpack

play12:01

it into this new object that I am

play12:04

creating that is assigned to new user

play12:07

and then I'm just then going

play12:09

to uh reference mock users. push new

play12:14

user and then I'm going to go and just

play12:18

return the new user and remember we want

play12:20

to send back a status code of

play12:23

200 or I'm sorry 2011 because if I were

play12:26

to send this right

play12:27

now you you can see that I do get back

play12:30

the user but it sends back sends me back

play12:31

a 200 and for good practice you want to

play12:34

make sure the post request sends a 2011

play12:36

so I can just set response. status call

play12:40

the status method and pass into a one

play12:42

and then call do send so we did this in

play12:46

an earlier part of the tutorial where we

play12:48

were making get requests right over here

play12:51

okay so let's go ahead

play12:53

and test this out click Send all right

play12:57

so you can see whenever I click send it

play12:59

will just keep creating a new user and

play13:02

it'll send it back to uh the client

play13:05

which is this uh Thunder client as a

play13:07

response and it has the ID Auto

play13:10

incremented so that's pretty

play13:17

cool

Rate This
β˜…
β˜…
β˜…
β˜…
β˜…

5.0 / 5 (0 votes)

Related Tags
Express APIPOST requestThunder ClientVS CodeAPI tutorialJSON parsingMiddlewareWeb developmentNode.jsHTTP requests