Sure, here is an example of an Express middleware to handle Cross-Origin ResourceSharing (CORS) for your MERN app:
JavaScript
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors({
origin: '*',
optionsSuccessStatus: 200,
}));
app.get('/', (req, res) => {
res.send('This is a CORS-enabled endpoint');
});
app.listen(3000, () => console.log('Server started on port 3000'));
This middleware first imports the express and cors modules. The
cors module provides a middleware that can be used to enable CORS for Express applications.
The middleware then defines the origin and optionsSuccessStatus options for the
cors() middleware. The origin option specifies the origins that are allowed to make cross-origin requests. The
optionsSuccessStatus option specifies the status code that should be returned when the CORS preflight request is successful.
The middleware then uses the use() method to add the cors() middleware to the Express application.
Finally, the middleware defines a get handler for the / route. The
get handler simply sends a message to the client indicating that the endpoint is CORS-enabled.
To run this middleware, you can save it as a file called cors.js and then run it from the command line:
node cors.js
This will start the Express server on port 3000. You can then test the endpoint by making a GET request to
http://localhost:3000/ from a browser or another application.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Sure, here is an example of an Express middleware to handle Cross-Origin Resource Sharing (CORS) for your MERN app:
JavaScript
This middleware first imports the
expressandcorsmodules. Thecorsmodule provides a middleware that can be used to enable CORS for Express applications.The middleware then defines the
originandoptionsSuccessStatusoptions for thecors()middleware. Theoriginoption specifies the origins that are allowed to make cross-origin requests. TheoptionsSuccessStatusoption specifies the status code that should be returned when the CORS preflight request is successful.The middleware then uses the
use()method to add thecors()middleware to the Express application.Finally, the middleware defines a
gethandler for the/route. Thegethandler simply sends a message to the client indicating that the endpoint is CORS-enabled.To run this middleware, you can save it as a file called
cors.jsand then run it from the command line:This will start the Express server on port 3000. You can then test the endpoint by making a GET request to
http://localhost:3000/from a browser or another application.