Understanding and Solving Cors Errors

backend#cors#backend#web development

Explanation

Watch this video where I explain what CORS errors are and their solution in concept.

CORS ERRORS

CORS IN EXPRESS

Refer to the code below to address CORS issues in Express, although my express template already has cors configured if you want to use it as your starting place.

npx merced-spinup expressrest projectName

// +& CONFIGURING CORS IN EXPRESS 
// +* INSTALL CORS MIDDLEWARE - npm install cors 

// +% CREATE YOUR CORS CONFIG OBJECT 
// +! Whitelist are URLS allowed to make requests to API
const whitelist = ['http://example1.com', 'http://example2.com']
const corsOptions = {
  origin: function (origin, callback) {
    if (whitelist.indexOf(origin) !== -1) {
      callback(null, true)
    } else {
      callback(new Error('Not allowed by CORS'))
    }
  }
}

// +% ADD MIDDLEWARE TO EXPRESS
// +! USE TERNARY OPERATOR TO TOGGLE BETWEEN ALLOWING ALL SOURCES AND WHITELIST
app.use(NODE_ENV === production ? cors(corsOptions) : cors())

Read Next

Ruby on Rails API with JWT Auth Tutorial
Web Components Part 1 - The Basics
Mongoose, Connecting to Mongo via Javascript