Enable CORS or Pre flight requests at NodeJS

Cros Origin Resource Sharing

This is how we can Enable CORS

const app = express();
/**
 * Changes made to enable CORS
 */
const allowCORS = (req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    //Method Supported
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    //If you have additional Headers which needed to be allowed
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, token');
    // intercept OPTIONS method, as all the preflight request first send the options method, and based
    // on the success, it will further allows the actual call.
    if ('OPTIONS' == req.method) {
        res.sendStatus(200);
    }else {
        next();}
};
//Allow cross domain.
app.use(allowCORS);


Comments