With two origins, the API needs CORS headers on every answer, and the browser sends an extra OPTIONS request before every JSON post. In development there is a simpler way: the page only asks its own origin. Vite's dev server, which serves the storefront at localhost:5173, can pass some paths on to another server. This is called a proxy.
The client is already changed: it asks /api/products, a path with no address in front, so the browser sends it to localhost:5173. The dev server doesn't know /api yet, so it answers with the page itself, HTML, and response.json() fails on the first character, <.
In vite.config.js, server.proxy maps the start of a path to the server that should answer it. For example, to pass every /images request to an image server on port 4000:
server: {
proxy: {
"/images": "http://localhost:4000",
},
},
Right now the check prints:
> open the page request: GET /api/products -> 200 (the page's own HTML, not JSON) alert: Could not load the products: Unexpected token '<', "<!doctype "... is not valid JSON
With the proxy it must print:
> open the page
request: GET /api/products -> 200
text: 8 products
> click "Send suggestion"
request: POST /api/suggestions {"name": "Kettle"} -> 201
status: Thanks! We got your suggestion: Kettle
Your task: in client/vite.config.js, add dev server settings with a proxy that sends every path starting with /api to http://localhost:3000. The API in server/app.js has no CORS headers, and it doesn't need them.
Assignment
Follow the Coding Tutorial to add server, then proxy inside it, then the /api entry, so the browser only ever talks to one origin.
Hintserver goes below plugins, separated by a comma. proxy is an object inside it, and each key is the start of a path in quotes.
Free plan: 30 tutor messages. PRO is unlimited.
