noe install cors code example

Example 1: express js cors

var express = require('express')
var cors = require('cors')  //use this
var app = express()

app.use(cors()) //and this

app.get('/user/:id', function (req, res, next) {
  res.json({user: 'CORS enabled'})
})

app.listen(5000, function () {
  console.log('CORS-enabled web server listening on port 5000')
})

Example 2: cors express

var allowedOrigins = ['http://localhost:3000',
                      'http://yourapp.com'];
app.use(cors({  
  origin: function(origin, callback){
    // allow requests with no origin     
    // (like mobile apps or curl requests)    
    if(!origin) 
      return callback(null, true);    
    if(allowedOrigins.indexOf(origin) === -1){
      var msg = 'The CORS policy for this site does not ' +                
          'allow access from the specified Origin.';      
      return callback(new Error(msg), false);    
    }    
    return callback(null, true);  
  }
}));

Tags:

Misc Example