Using CORS in Koa

Using of Cross-Origin Resource Sharing (CORS) in your Koa.js server requires the installation of koa2-cors library. You can install it using the following:

The simple server with default CORS will be looks like this:

Let’s make a test request from another server to our server (port 3000). We can do this using the fetch:

You should see the next result in developer tools:

CORS in Koa framework

If we replay request to our server, but without enabled CORS, the result will be another:

Koa server without CORS

The cors method takes one object with the following properties:

  • origin – string or function that returns a string;
  • exposeHeaders – an array of strings;
  • maxAge – number;
  • credentials – boolean;
  • allowMethods – an array of strings;
  • allowHeader – an array of strings;

More detailed information you can read on the official NPM page of the library.

If you liked this, please help spread the word by hitting the recommend button below. Thanks!

Tags:, ,