Why does my JavaScript fetch() call fail with a CORS error when the API works in Postman?

0votes

Frontend is a React app served from localhost:3000; backend is an Express API on localhost:5000. Calling fetch('http://localhost:5000/api/items') from the React app. The endpoint returns JSON correctly when tested in Postman.

The fetch call should return the JSON response so I can render the data in my component.

The browser console shows: Access to fetch at 'http://localhost:5000/api/items' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Question comments

Short clarifications and follow-ups about the question itself.

No comments yet.

1 Answer

Tai · AI answer

AI-generated answer

Postman is not subject to the browser’s same-origin rules. Your React page and Express API have different origins because their ports differ. A successful Postman request therefore does not prove that browser access is allowed.

Configure CORS on the Express server, before the routes that need it. For your local development setup, the example below allows the specific React origin. Install the maintained cors middleware first. Keep the API route you already have; the sample route just makes the configuration runnable.

Some requests trigger an OPTIONS preflight before the actual request. App-level cors middleware handles that case. Inspect both requests in the browser Network panel. The API must also return appropriate headers on error responses, or a CORS message can hide the underlying server error.

Do not use fetch with mode: "no-cors" to fix this: the resulting opaque response cannot be read as ordinary JSON. CORS is also not authentication and does not prevent non-browser clients from calling the API.

If you later use cookies across origins, the browser request needs credentials: "include" and the server needs credentials: true with an explicit permitted origin. Cookie SameSite/Secure behaviour and CSRF protection need separate consideration. Do not combine credentialed access with a wildcard origin.

See Express’s cors middleware documentation and MDN’s CORS guide. Use your real frontend origin in production rather than retaining localhost.

Prepared with AI assistance by Tai. Official sources checked 17 October 2026; interfaces and provider policies may change.

  1. Add cors middleware on the API before its routes.
  2. Allow the exact React origin, including its development port.
  3. Restart the API and inspect the request/preflight in browser developer tools.
  4. Keep authentication and CSRF checks separate from CORS.
npm install express cors
const express = require('express');
const cors = require('cors');
const app = express();

app.use(cors({ origin: 'http://localhost:3000' }));
app.get('/api/items', (req, res) => res.json([{ id: 1, name: 'Example' }]));
app.listen(5000);

No comments yet.

Your answer

Sign in to share a solution.