Understanding and Solving Cors Errors

Explanation

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

http://www.youtube.com/watch?v=fsMKB7PJoFY

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())

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store