CORS error when calling my Node.js API from frontend #29
-
|
I built a small Express API and a React frontend. Access to fetch at 'http://localhost:4000/api/data' from origin 'http://localhost:3000' has been blocked by CORS policy. My backend looks like: const express = require('express'); What do I need to fix? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
You need to enable CORS (Cross-Origin Resource Sharing) so your frontend (port 3000) can talk to your backend (port 4000). Install the cors middleware: const express = require('express'); app.use(cors()); // allow all origins app.get('/api/data', (req, res) => res.json({ message: 'Hello' })); If you want to limit it: app.use(cors({ origin: 'http://localhost:3000' })); That fixes the CORS error. |
Beta Was this translation helpful? Give feedback.
You need to enable CORS (Cross-Origin Resource Sharing) so your frontend (port 3000) can talk to your backend (port 4000).
Install the cors middleware:
Then update your server:
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors()); // allow all origins
app.get('/api/data', (req, res) => res.json({ message: 'Hello' }));
app.listen(4000);
If you want to limit it:
app.use(cors({ origin: 'http://localhost:3000' }));
That fixes the CORS error.