Start learning free

LESSON 29 OF 58 · FULL-STACK: CART AND CHECKOUT

Check on the Server in JavaScript

Practice

The checkout page sends the visitor's name, address and postal code to POST /api/checkout. Before the shop does anything with an order, the server must check them. The page can check too, but anyone can send a request without the page, so only the server's check counts.

When something is wrong, answer 400 Bad Request and say exactly what: one message per wrong field, under the field's name, all in one answer. Here is the idea on another route, a review form:

app.post("/api/reviews", requireLogin, (req, res) => {
  const fields = {};
  if (isBlank(req.body.text)) {
    fields.text = "Text is required";
  }
  if (!(req.body.stars >= 1 && req.body.stars <= 5)) {
    fields.stars = "Stars must be 1 to 5";
  }
  if (Object.keys(fields).length > 0) {
    return res.status(400).json({ error: "Check the form", fields: fields });
  }
  res.status(201).json({ ok: true });
});

The given isBlank is true for a missing value, a value that is not a string, and a string of spaces like " ". A postal code must be exactly 5 digits: /^[0-9]{5}$/.test(value) says whether it is. And an order needs something to order: an empty cart answers 400 before the form is even looked at. Nothing is saved yet in this lesson.

Ana has a Mug and a Lamp in her cart. Ben's cart starts empty, then gets a Teapot:

Ana: Place order (Ana Pop, no address, 4000)  →  400  alert: Check the form
Ana: Place order (all filled, 40001)          →  200  Ready to pay: $41
POST /api/checkout  (Ben, empty cart)         →  400  {"error": "Your cart is empty"}
POST /api/checkout  {}                        →  400  {"error": "Check the form", "fields": {"address": "Address is required", "name": "Name is required", "postal_code": "Postal code must be 5 digits"}}
POST /api/checkout  (address "   ")           →  400  {"error": "Check the form", "fields": {"address": "Address is required"}}
POST /api/checkout  (all filled)              →  200  {"total": 22}

Your task: in the checkout route of server/app.js, answer 400 for an empty cart, then collect a message for each wrong field in fields and answer 400 "Check the form" with all of them.


Assignment
Follow the Coding Tutorial to check the cart and the checkout form on the server, and answer 400 with every wrong field at once.


Hint
Use three separate ifs, not else if, so every wrong field gets its message. Send the 400 only after all three checks, when Object.keys(fields) is not empty.


STEP 1 OF 11
    Ctrl + Enter to check

    Fscheckout Validate in JavaScript

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free