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 require
ign 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.