Answer
To fix CORS errors in your Express API, you need to configure the `cors` middleware correctly. Ensure you require and use the middleware 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 methods: ['GET', 'POST'], // Allow specific HTTP methods allowedHeaders: ['Content-Type', 'Authorization'] // Allow specific headers })); app.get('/api/data', (req, res) => { res.json({ message: 'Hello from the backend!' }); }); app.listen(5000, () => { console.log('Server running on http://localhost:5000'); }); ``` Make sure the `cors` middleware is placed before any route definitions. This configuration allows requests from `http://localhost:3000` and specifies allowed methods and headers.
45cd900f-1e18-49dd-b965-b40e9994b781
To fix CORS errors in your Express API, you need to configure the cors middleware correctly. Ensure you require and use the middleware 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
methods: ['GET', 'POST'], // Allow specific HTTP methods
allowedHeaders: ['Content-Type', 'Authorization'] // Allow specific headers
}));
app.get('/api/data', (req, res) => {
res.json({ message: 'Hello from the backend!' });
});
app.listen(5000, () => {
console.log('Server running on http://localhost:5000');
});Make sure the cors middleware is placed before any route definitions. This configuration allows requests from http://localhost:3000 and specifies allowed methods and headers.