Express Production Setup - 3 | CORS
Express Production Setup - 3 | CORS
To enable Cross-Origin Resource Sharing (CORS) in an Express.js application, you can use the cors
middleware package. This middleware allows you to control which domains can access your API, what methods are allowed, and what headers can be sent in requests.
index.js
const express = require('express');
const cors = require('cors');
const app = express();
// CORS options to allow only POST requests
const corsOptions = {
origin: 'http://example.com', // Replace with your client's origin
methods: ['POST', "GET", "PUT", "PATCH", "DELETE"],
credentials: true // allow cookies
};
// Apply CORS middleware with the above options
app.use(cors(corsOptions));
// Example route
app.post('/api', (req, res) => {
res.json({ message: 'This is a POST request endpoint with CORS enabled!' });
});
// Handle other routes or methods (GET, PUT, DELETE, etc.)
app.use((req, res) => {
res.status(405).send('Method Not Allowed'); // Send 405 for methods other than POST
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Comments
Post a Comment