CPNT 262 Day 22 - Handling POST Requests with Mongoose

Housekeeping

Trophy of the day

  • Deployed express server with mongoose

1. POST requests with request.body and express.urlencoded()

Materials

Key Takeaways

  • The request object stores parameters in three main objects:

    1. req.params: Parameters passed as route segments.
      • Example: GET /api/animals/:id.
    2. req.query: Parameters passed after the ? in a URL.
      • Example: /api/animals?page=3&per_page=10.
    3. req.body: Parameters passed in the request body, such as when a form is submitted with method="POST".
  • req.body is only available if you add the following middleware to your server file:

    app.use(express.urlencoded({ extended: true }));
  • Alternatively, you can add the following if the form was submitted in JSON format (not covered in this course):

    app.use(express.json());
    • Both can be added at the same time and both will process POST form parameters and add them to req.body
  • The form submission is handled by app.post() at the same path as your list entry endpoint. The method is set by the method attribute in your form:

    app.post('/api/kittens', () => {...})

2. Creating Mongoose records

Materials

Key Takeaways

  • Saving a record with Mongoose requires two steps:

    1. Creating a model instance, passing an object containing the information submitted by the form.
      const kitten = new Kitten(req.body)
    2. Saving the instance with model.save():
      await kitten.save()
  • Since we didn't cover view engines in express, we will be redirecting to static success and fail pages depending on the result of the .save()

    response.redirect('/success.html')

    OR

    response.redirect('/fail.html')

3. Deploying to Heroku with Atlas

Materials

Key Takeaways

  • Most of the steps in this tutorial were completed yesterday so you should only have to complete the following to have your Heroku connect to Atlas:
    • Add your connection string to the Config Var section of your App Settings with a name of MONGODB_URL (Important: Heroku won't connect to Atlas properly unless you use this variable name).
  • Note: CORS is probably not needed for your app to operate.

Lab Time

  • Trophy of the day
  • Assignment 5
  • Final Project

Prep

POST Requests with Express and Mongoose

Deploying with Atlas on Heroku