The storefront and the API are two programs at two addresses. The page comes from http://localhost:5173, and its code asks http://localhost:3000/api/products for the products. An origin is the scheme, the host and the port of an address, so another port means another origin.
Under the same-origin policy, a browser hides an answer from another origin from the page. The only exception is an answer that gives this page permission with the header Access-Control-Allow-Origin. The API answers 200, but the page only sees Failed to fetch.
A header that belongs on every answer goes in a middleware: a function Express runs before the routes, in the order you add it with app.use. It gets req, res and next, and calls next() to pass the request on. This one marks every answer with the shop's name:
function addShopName(req, res, next) {
res.set("X-Shop", "Corner Shop");
next();
}
app.use(addShopName);
Right now the check prints:
> open the page
request: GET http://localhost:3000/api/products -> blocked by the browser (CORS):
the answer has no Access-Control-Allow-Origin header
alert: Could not load the products: Failed to fetch
text: 0 products
Your server must make it print:
> open the page request: GET http://localhost:3000/api/products -> 200 text: 8 products item: Mug $12 item: Notebook $7 Out of stock …
Your task: in server/app.js, write a middleware that sets Access-Control-Allow-Origin to the storefront's origin, http://localhost:5173 (not *). Register it above the routes.
Assignment
Follow the Coding Tutorial to write the middleware allowStorefront, register it with app.use, and let the storefront read the products.
Hint
An origin has no slash at the end: "http://localhost:5173". Set the header with res.set before you call next().
Free plan: 30 tutor messages. PRO is unlimited.
