Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Add a POST Route To Express And Parse the Body


    In this lesson, we see how to handle POST requests on our server and we extract the data that was passed in the body of the requests using body-parser.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    Instructor: In order to handle our first post request, we will use Express' post method. We will create a route that handles user logins.

    The first argument is a route, which is /login in our case. The second argument is a callback with the request and response arguments.

    Let's now define a constant that will contain the name of the user that was posted to disrupt. The constant name user will have the value of the username property that was passed in our request as a JSON object.

    At this point, Express can't read the body of their request. We will need to require an additional middleware call body-parser. We can also go into terminal to install this new library.

    Now that it's installed, we can add the middleware to Express using the use method. We will specify that it will handle JSON responses.

    We are now able to read the request body, so our constant contains the username that was passed into login route. We are ready to build our response, which has a status of 200 because this is a success.

    We will send back a simple string that says, "You logged in with user." It will display the username that we just received.

    Let's start our server using node and the name of the file. This is now listening on port 3000, which was defined as an environment variable previously.

    To test this new route, we can use postman. If we try to do a get request, we are getting a, "404, Page not found," because we don't handle that request anymore.

    Now, we can do a post request to the login route. Let's start by specifying the body of our request. It will be a JSON object with a username property. Make sure that you changed the content type to applications.json.

    If we run this, you get a, "You logged in with username," message. That is how you parse a post request and handle the request data.