Skip to content

Instantly share code, notes, and snippets.

@christroutner
Created April 27, 2018 18:10
Show Gist options
  • Save christroutner/07189da21c466d5f2a29451099c8a165 to your computer and use it in GitHub Desktop.
Save christroutner/07189da21c466d5f2a29451099c8a165 to your computer and use it in GitHub Desktop.
koa2 Access-Control-Allow-Origin CORS example

It took me way too long and way too much trial and error to figure out how to turn on Cross Origin Resource Sharing (CORS) on my Koa 2 API. The problem is that there are too many ways and too many versions of all the pieces. It's not difficult if you follow the example below.

Note: You can download working code using this Koa 2 API Boilerplate repository.

The key insight that finally enabled me to success was this blog post, which used kcors library in favor of the koa-cors library.

In the bin/server.js file, I only needed to add this line, after requireign the kcors library.

app.use(cors({origin: '*'}))

The * allows all domains, which is a big security risk. But most developers, like me, enable this to allow quick prototyping.

You're welcome.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment