userMod2
userMod2

Reputation: 8960

Node/Express - Otherwise Route and CORS

I'm getting a Node/Express API ready for production however have some questions/advice need help on:

1 - I'm using the npm package cors - did so for development to basically disable CORS, however now that I'm moving to production I only want certain URLS to be able to reach the API.

So to so this what I've seen is:

var corsOptions = {
  origin: 'http://www.example.com',
  methods: ['GET', 'POST']
};

app.get('*', cors(corsOptions), function(req, res, next) {
  res.json({msg: 'This is CORS-enabled for only example.com.'});
});

However (from what I've seen) I'd need to do this for everyone request type e.g.

app.post('*', cors(corsOptions), function(req, res, next) {
      res.json({msg: 'This is CORS-enabled for only example.com.'});
});

app.del('*', cors(corsOptions), function(req, res, next) {
      res.json({msg: 'This is CORS-enabled for only example.com.'});
});

Is there an easier way to avoid such duplication?

2 - And the second question - I have a long list of API routes e.g.

router.post('/registerUser', function(req, res) {
  ...
}

Is it possible to place some kind of 'otherwise' line so that if a route doesn't match anything I've defined i can return something specific?

Thanks.

Upvotes: 0

Views: 1079

Answers (1)

Nivesh
Nivesh

Reputation: 2603

For first put cors as a middleware before your first route.

   app.use(cors(corsOptions));
    //routes down below

Explanation: Cors will be set for all the routes below for every request. As this middleware will be executed first.

For second put your otherwise or 404 route after your last route.

app.use((req,res,next)=>{
   //Your message
   res.send('Page Not Found');
});

Explanation: If any route will not be matched then this route will trigger.

Upvotes: 1

Related Questions