Build an Express middleware to handle Cross-Origin Resource Sharing (CORS) for your MERN app.
Build an Express middleware to handle Cross-Origin Resource Sharing (CORS) for your MERN app.
28326-Jul-2023
Updated on 27-Jul-2023
Home / DeveloperSection / Forums / Build an Express middleware to handle Cross-Origin Resource Sharing (CORS) for your MERN app.
Build an Express middleware to handle Cross-Origin Resource Sharing (CORS) for your MERN app.
Aryan Kumar
27-Jul-2023Sure, 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
express
andcors
modules. Thecors
module provides a middleware that can be used to enable CORS for Express applications.The middleware then defines the
origin
andoptionsSuccessStatus
options for thecors()
middleware. Theorigin
option specifies the origins that are allowed to make cross-origin requests. TheoptionsSuccessStatus
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 thecors()
middleware to the Express application.Finally, the middleware defines a
get
handler for the/
route. Theget
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: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.