Using CORS in Koa


cors koa nodejs Tutorials

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:

npm install koa2-cors -s

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

const Koa = require('koa');
const cors = require('@koa/cors');

const app = new Koa();
app.use(cors());
app.use(function(ctx) {
    ctx.body = { status: 'OK' };
});

app.listen(3000, () => console.log('Server is works'));

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

fetch('http://localhost:3000/')
  .then(response => response.json())
  .then(data => console.log(data))

You should see the next result in developer tools:

Access-Control-Allow-Origin Header

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

Koa error

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.

comments powered by Disqus