Start learning free

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

One Address in Development in JavaScript

Practice

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.


Hint
server goes below plugins, separated by a comma. proxy is an object inside it, and each key is the start of a path in quotes.


STEP 1 OF 3
    Ctrl + Enter to check

    Fs Dev Proxy 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