Problem Overview
Cross-Origin Resource Sharing (CORS) is essential for allowing your web applications to request resources from different origins. Here's how to implement CORS in a Node.js application:
const express = require('express');
const cors = require('cors');
const app = express();
// Use CORS middleware
app.use(cors());
app.get('/api/data', (req, res) => {
res.json({ message: 'Hello from CORS-enabled server!' });
});
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
By including the CORS middleware, your Node.js application will now accept requests from any origin. You can configure the cors
package further to specify allowed origins, methods, and headers, ensuring you maintain security while offering flexibility.