CORS in Express.js
The following code adds the Access-Control-Allow-Origin
and Access-Control-Allow-Headers
headers globally to all requests on all routes in an Express.js application. A route
is a path in the Express.js application, for example, /user
for a user page. app.all
sets the configuration for all routes in the application. Specific HTTP requests such as GET
or POST
are handled by app.get
and app.post
:
app.all('*', function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With"); next(); }); app.get('/', function(req, res, next) { // Handle GET for this route }); app.post('/', function(req, res, next) { // Handle the POST for this route });
For better security, consider limiting the allowed origin to a single domain, or adding some additional code to validate or limit the domain(s) that are allowed. Also, consider limiting sending the headers only to routes that require CORS by replacing app.all
with...