Node.js API
Node.js API CORS Error Fix
Clear a browser CORS block so a separate-origin frontend can call your Node.js API by installing the cors package, enabling it before routes, and optionally locking allowed origins.
Before you start
- Do not leave every origin allowed on a production server. Lock the allowed origin to your real frontend URL.
- Run the install and middleware change in the server project folder, not the frontend folder.
- Restart the server after saving or the change will not load.
Tools
- terminal
- code editor
- web browser
Parts
cors npm package
- 01
Confirm the cross-origin block
Reproduce the failing API call from the frontend. Note the browser error that no Access-Control-Allow-Origin header is present. Treat this as the browser blocking a request whose origin does not match the API host.
- 02
Install cors in the server folder
Open a terminal in your backend project root. Install the cors package with npm so the server can send the needed CORS headers. Wait for the install to finish before editing files.
Make sure the terminal is in the server folder, not the React or other frontend app.
- 03
Enable cors before your routes
Open the main server file. Import cors and keep a reference to it. Register cors as application-wide middleware ahead of every API route so preflight and normal requests get CORS headers. Save the file.
- 04
Restart and retest with open origins
Restart the Node server so the new middleware loads. Refresh the frontend and repeat the same request. Confirm the response data returns and the CORS error is gone. Know that this default setup allows requests from any origin.
- 05
Lock cors to your frontend origin
Change the cors registration to take a small options object. Set origin to your frontend base URL only, such as http://localhost:3000 for local React. Save, restart the server, and confirm your frontend still reads data.
A request from any other origin should now fail. Do not widen origin again unless you intend to allow that host.
- 06
Verify rejected foreign origins
If you can, call the API from a different origin than the one you allowlisted. Confirm that call is blocked while your real frontend still works. Leave the allowlist limited to hosts you trust.
Was this accurate?
Rate the written steps, not the original video. One vote per browser.