Until now, the Vite dev proxy passed every /api request from the page's own address to the API, so the page and the API looked like one site. In this lesson the proxy is gone: the storefront runs at http://localhost:5173 and the API at http://localhost:3000. An origin is the scheme, the host and the port together, so a different port makes a different origin.
Across origins the browser is careful. A path alone, like "/api/login", would go to the page's own origin, so api() must call the API's full address. A JSON request is first checked with an OPTIONS request, the preflight. And by default fetch neither keeps the cookies another origin sets nor sends any to it. The login seems to work, until the reload: the session cookie was never kept.
To carry cookies, both sides must agree. The server answers Access-Control-Allow-Credentials: true (the given server already does), and each request asks with credentials: "include":
const response = await fetch("http://localhost:3000/api/orders", {
credentials: "include",
});
The check logs in as Ana, reloads the page, then sends a preflight itself:
POST http://localhost:3000/api/login → 200 header: Logged in as ana@example.com reload the page GET http://localhost:3000/api/me → 200 header: Logged in as ana@example.com OPTIONS /api/me → 204 Access-Control-Allow-Credentials: true
Without credentials, that GET /api/me answers 401 and the visitor is logged out after the reload.
Your task: in client/src/api.js, call the API at http://localhost:3000, and give fetch the method, the JSON header, the body as JSON and credentials: "include".
Assignment
Follow the Coding Tutorial to write the fetch in api() one option at a time, ending with the credentials.
Hint
Every option goes inside the object after the URL: fetch(API_URL + path, { … }). Each option line ends with a comma.
Free plan: 30 tutor messages. PRO is unlimited.
