Node express cors and routes

2019-05-07 06:42发布

问题:

I am using CORS https://www.npmjs.com/package/cors to allow whitedomain list.

   var whitelist = ['http://example1.com', 'http://example2.com'];
var corsOptions = {
  origin: function(origin, callback){
    var originIsWhitelisted = whitelist.indexOf(origin) !== -1;
    callback(null, originIsWhitelisted);
  }
};

app.post('/products/:id', cors(corsOptions), function (req, res, next) {
    console.log(0);
    res.json({ msg: 'This is CORS-enabled for a whitelisted domain.' });        
});

In case of non whitedomain the server returns No 'Access-Control-Allow-Origin' which is fine but at the same time I can see on debug that the lines res.json({ msg: 'This is CORS-enabled for a whitelisted domain.' }); and console.log(0); still gets executed - console.log(0); printed 0 in console on server side which is something I do not wan't in that case.

So lets say if is writhing to database:

app.post('/products/:id', cors(corsOptions), function (req, res, next) {
        writeToDatabase();
        res.json({ msg: 'This is CORS-enabled for a whitelisted domain.' });            
    });

This way writeToDatabase(); will always be executed. But I want to avoid that because I do not need to write any stuff in to database in case of non whitelisted domain.

Any thoughts?

回答1:

My idea is to use if to filter the request inside the app.post so for example,

app.post('/products/:id', cors(corsOptions), function (req, res, next) {
        if(req.header[origin]===whitelisted){
        writeToDatabase();
        res.json({ msg: 'This is CORS-enabled for a whitelisted domain.' }); }           
    });