Answer
To fix CORS errors in your Express API, you need to configure the `cors` middleware correctly. Ensure you're using `express` version 4+ and install `cors` via `npm install cors`. Then, in your Express app: ```js const express = require('express'); const cors = require('cors'); const app = express(); app.use(cors({ origin: 'http://localhost:3000' })); // Allow only your frontend origin app.get('/api/data', (req, res) => { res.json({ message: 'Hello from backend!' }); }); app.listen(5000, () => console.log('Server running on port 5000')); ``` Make sure the `cors` middleware is used before any route definitions. If you want to allow all origins temporarily for development, use `origin: '*'`, but always restrict it in production.
272c6bef-7510-4b1a-bdf7-879cd8cb6aca
To fix CORS errors in your Express API, you need to configure the cors middleware correctly. Ensure you're using express version 4+ and install cors via npm install cors. Then, in your Express app:
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors({ origin: 'http://localhost:3000' })); // Allow only your frontend origin
app.get('/api/data', (req, res) => {
res.json({ message: 'Hello from backend!' });
});
app.listen(5000, () => console.log('Server running on port 5000'));Make sure the cors middleware is used before any route definitions. If you want to allow all origins temporarily for development, use origin: '*', but always restrict it in production.