Express JS #5 - Post Requests
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
π¨ 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.
π¨ 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.
π© 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
π‘POST Request
π‘Request Body
π‘Express API
π‘Middleware
π‘Thunder Client
π‘JSON
π‘Status Code
π‘API Route
π‘Array
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
now that you all know how to retrieve
data from the express API using get
requests I'm going to show you how you
can create data using what is called a
post
request now let's say for example you
want to create a resource on the backend
and that backend will save it to a
database or save it to a file or save it
just somewhere doesn't matter where it
is you want to create let's say a user
so your client your front end
application will have a user form they
fill out their username password email
and other additional Fields once they
are ready they will click that sign up
button when you click that sign up
button it will make an API request to
the backend doesn't have to be
necessarily an Express API server it can
be really any API server that's running
that handles that post request okay so
the front end the client side would make
an HTTP request a post request to the
server okay once the server receives
that request the server needs to
obviously be able to grab the data that
we're trying to send from the client
side to the back end and that data that
you're sending is known as a request
body so whenever you make post requests
the data that you want to send to the
backend server you send it via a payload
or a request body you use those terms
synonymously so payload request body are
interchangeable terms the backend will
then take that data and it will perform
the necessary operations in need so
typically validation if it need to do
additional parsing if it needs to make
sure that it has the proper Fields it
will do all that stuff before it can
proceed with either saving it to a
database or saving it to some external
API Source whatever it is I need to do
once it's done saving that record to the
database or somewhere it will return a
2011 response which or 2011 status code
which typically just means that the
resource was created sometimes it might
also return the new record that was
created so that way if you need to use
it on the client side for whatever
reason you can do so now before we
actually can make any post requests we
do need an HTTP client to actually uh
make those requests and also be able to
send a request body to our Express API
because on the browser there's no
built-in tool that enables you to send
requests bodies unless if you to write
the code in the JavaScript console but
we're not going to do that um so there
are different uh clients that you can
use to interact with your API So
currently we've just been using the
browser which we limited to just making
get requests by simply typing in the
address in the address bar we want to be
able to make post requests where we can
send actual data okay so you can use
tools like Postman there's also
Hopscotch which is an alternative to
postman for for this tutorial I'm going
to keep things simple I'm going to keep
everything inside vs code and we're
going to install this extension so on
the left hand side or um wherever you
have this extensions icon just click on
extensions and you want to search for an
extension called Thunder
client and thunder client is a very
lightweight rest API tool for VSS code
it's integrated in there you just have
to install it and it allows you to make
API calls to your Express server
so I'll go ahead and click
install Okay and then I'm going to go
just close
this and then let's go ahead on the left
hand side you should see the Thunder
client appear right over here as an icon
that's the Thunder client and I'll click
on it and
now what I can do is I can create a new
request by clicking on the new request
button and you can see now it looks it
it looks kind of identical to to postman
if you've used it before or really any
other rest client but we have an address
bar where we can uh type in the address
or the URL that we want to make requests
to so I'll type in Local Host Port
3000 / API users I'll make a get request
so I can select this drop down and
select get and I'll click Send and you
can see that it gives us back the
data just like that okay and we're going
to use this client to switch between
different types of HTTP requests that we
want to make so we'll switch from get to
post and then in later videos when I
show you how to handle put requests or
delete requests we will switch to these
HTTP requests as well okay so let's
close this out just wanted to show you
all how to set up thunder client so now
what I'm going to do is set up our post
request to be able to create a brand new
user so what I'm going to do is right
underneath my
uh API users route I'll go ahead and
reference the app variable and since I
want to register a post request I'm
going to go ahead and call the Post
method so this method is very similar to
all the other HTTP verb methods such as
get put delete uh it takes in a path so
over here I'm going to go and pass
inapi users now you're probably
wondering well should we be able to
reuse the path and the answer is yes
because you have a different HTTP
request type being used so this is for
post request and the one over here is
for get requests okay when your HTTP
client is making requests the server
knows if it's making a get or a post
request so that way there's no
confliction between these two different
types of requests despite the route
being the same so we'll also pass in in
a request and
response or we'll pass in the request
Handler function which will have these
two arguments request and response and
then for now I will just return a
response. send I'll just pass in a 200
status code or I'll just pass in 200 and
I'll just console log the request body
just so that we can see what our data is
looking like when we send it from the
client so let's go back to thunder
client so I'll click on the Thunder icon
I'll click on new request and up top
where you see gets just click on that
drop down and select post and we're
going to change the url and we're going
to type in Local Host Port 3000 API
users okay so once again we have uh we
have two different types of
HTTP uh methods but they both use the
same path okay so whenever I call a post
request to API users I don't even need
to send any data for now it's just going
to give me back a 200 status
code now I can go into the body tab in
my thunder client and I can select Json
if I want to send Json so if I try to
send a request body let's see what
happens let's click Send so in the
console log for our in our terminal you
can see that right now it's actually
logging undefined on I try to send it
again it still logs undefined and you're
probably wondering well what's going on
with this why is it undefined well the
reason why it's undefined is because
right now by default Express is not
parsing those request bodies that are
coming in so whenever I am sending Json
to the express server the headers set
the content type to application Json
Express doesn't parse those payloads by
default so we need to tell Express to do
so now this is going to require us to
use a middleware so this is kind of like
a brief little intro to middlewares but
don't worry so much about it once we
actually get into the topic of
middlewares you'll better understand how
they work but all of middleware is is
just a function that is going to be
invoked before uh certain API requests
are being handled so in my case I want
to make sure that right before my post
request is being received I want to make
sure that that middleware that parses
the Json payload accordingly is being
invoked so you typically want to
register your middleware as early as
possible so the best way to do it is
doing it up top after you create your
Express app instance so I'm going to go
ahead and reference app and I'm going to
call the use method and this is the
method that you use to register
middleware and the middleware that we're
going to register is actually already
built into Express so I can just
reference Express and call this
Json
method okay so now you can even read
over here it looks at requests where the
content type header matches the type
option so in this case this is express.
Json there's also other um uh there's
also other things that you can uh parse
to like let's say if you're trying to
send text or if you're trying to send uh
URL encoded or raw data so hopefully
that makes sense so in our case we'll
keep it as
Json and let's go ahead and see what
happens if I send the request
again so let's go back into
our ther client I'll click
Send I'll just click it again and now
watch this you can see that in the
console it is logging that
request that that request body that I am
sending to the express server and I can
literally add as many fields as I want I
can add a display
name let's do Anson
the dev click Send again and you can see
that it is is being logged right over
here okay perfect all right
cool now let's go ahead and actually do
something with the data so like I said
right now we don't have an actual
database so all I'm going to do is just
push this user to the array
so uh to do that what we'll do is we'll
assume that the request body is valid
but then in the next section I'm going
to show you how we can actually validate
the request body so I'm going to go
ahead and create a variable called new
user equals so we need to actually grab
all of the fields from the request body
but we also need to attach an ID to the
request body and once again since we
don't have a database to manage our uh
IDs because typically the database is
responsible for generating those
IDs all I'm going to do is just take uh
the last element the last user in the
mock user array uh take the ID of that
last user add one to it and assign that
to the new user the new new user's ID
okay so what I'll do is I'll first do
this mock users so I'm just going to
reference mock users um and then I'm
going to want to get the last element so
mock users. length minus
one okay so the length of our array is
going to be 7 and I want to reference
the last element so that's going to be
at index 6 because remember arrays are
indexed at
Aras are zero and next and then we're
going to reference ID and just add one I
know this is kind of like a hacky way to
do it but I just want I'm just doing it
just for a very simple example and then
what I'll do is I'm just going to
sign uh or I'm going to destructure the
request
body so I'm going to destructure body
from the request object and then I'll
just simply use the spreader operator on
the body object to take all of the
fields from the body object and unpack
it into this new object that I am
creating that is assigned to new user
and then I'm just then going
to uh reference mock users. push new
user and then I'm going to go and just
return the new user and remember we want
to send back a status code of
200 or I'm sorry 2011 because if I were
to send this right
now you you can see that I do get back
the user but it sends back sends me back
a 200 and for good practice you want to
make sure the post request sends a 2011
so I can just set response. status call
the status method and pass into a one
and then call do send so we did this in
an earlier part of the tutorial where we
were making get requests right over here
okay so let's go ahead
and test this out click Send all right
so you can see whenever I click send it
will just keep creating a new user and
it'll send it back to uh the client
which is this uh Thunder client as a
response and it has the ID Auto
incremented so that's pretty
cool
Browse More Related Video
Notion and iOS Shortcuts - Add Item To Database using the API
Express JS #3 - Route Parameters
Flask AJAX Tutorial: Basic AJAX in Flask app | Flask casts
MERN quiz creator app Part 2: Creating a database, Creating a basic api, adding JWT authentication.
[Legacy] Use Firebase for Auth in Wized
ReactJS Music Player #4: Integrating the Spotify Api in our React App
5.0 / 5 (0 votes)