Answer
To fix CORS errors in your Express API, you need to configure the `cors` middleware properly. Ensure you require and use it before defining your routes: ```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 port 5000'); }); ``` Make sure the server is running and the middleware is correctly applied. This configuration allows requests from `http://localhost:3000`.
a45cd7e3-0584-4a82-b1ca-223fe2893e5f
To fix CORS errors in your Express API, you need to configure the cors middleware properly. Ensure you require and use it before defining your routes:
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 port 5000');
});Make sure the server is running and the middleware is correctly applied. This configuration allows requests from http://localhost:3000.