Understanding and Solving CORS and CORS Errors (Express Snippets)

Alex Merced - Oct 20 '20 - - Dev Community

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())
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .