Node express courses and routes

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

   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.' });        
});

If non whitedomainthe server returns No 'Access-Control-Allow-Origin', which is excellent, but at the same time I can see when you debug that line res.json({ msg: 'This is CORS-enabled for a whitelisted domain.' });and console.log(0);still run - console.log(0);printed 0to the console on the server side, in this case, I do not want.

So let's say if he feeds the database:

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

This method writeToDatabase();will always be executed. But I want to avoid this because I do not need to write any things to the database in case of a domain non whitelisted.

Any thoughts?

+4
1

- , app.post ,

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.' }); }           
    });
0

All Articles