Start learning free

LESSON 2 OF 58 · FULL-STACK: TWO PROGRAMS, ONE APP

The Browser Asks First

Practice

A browser sends a plain GET to another origin right away, then checks the answer's Access-Control-Allow-Origin. Some requests are different. A POST with JSON, sent with the header Content-Type: application/json, is something an old HTML form could never send. For those, the browser first asks the server with a request that uses the method OPTIONS: the preflight. The real request goes out only if the answer says yes.

The preflight says what the real request will be. Say a page at http://localhost:5173 wanted to send a DELETE with a header X-Token. The browser would ask first:

OPTIONS /api/cart/4
Origin: http://localhost:5173
Access-Control-Request-Method: DELETE
Access-Control-Request-Headers: x-token

The server's yes would carry Access-Control-Allow-Origin, Access-Control-Allow-Methods: DELETE and Access-Control-Allow-Headers: X-Token.

No route has anything to add to a preflight, so the CORS middleware answers it itself: status 204 (No Content) with an empty body, and a return so that next() is not called. Browsers let GET and POST through even without Access-Control-Allow-Methods, but a Content-Type header with a JSON value must be listed in Access-Control-Allow-Headers.

Your app must answer:

OPTIONS /api/suggestions  →  204  (empty body)
    Access-Control-Allow-Origin: http://localhost:5173
    Access-Control-Allow-Methods: GET, POST
    Access-Control-Allow-Headers: Content-Type
POST /api/suggestions {"name": "Kettle"}  →  201  (the form shows: Thanks! We got your suggestion: Kettle)

Your task: in allowStorefront in server/app.js, below the line that sets the origin, answer OPTIONS requests with status 204, Access-Control-Allow-Methods: GET, POST and Access-Control-Allow-Headers: Content-Type.


Assignment
Follow the Coding Tutorial to answer the browser's preflight in allowStorefront, so the given "Suggest a product" form starts working.


Hint
req.method holds the method in capitals. Set the two headers before you send the 204, and put return in front of the answer so the function stops there.


STEP 1 OF 4
    Ctrl + Enter to check