What is @koa/cors?
@koa/cors is a middleware for Koa.js that enables Cross-Origin Resource Sharing (CORS) with various configuration options. It allows you to specify which origins are permitted to access your resources, as well as other CORS-related settings.
Basic CORS Setup
This code sets up a basic Koa server with CORS enabled for all origins. It uses the @koa/cors middleware without any additional configuration.
const Koa = require('koa');
const cors = require('@koa/cors');
const app = new Koa();
app.use(cors());
app.listen(3000);
Restricting Origins
This code configures the @koa/cors middleware to only allow requests from 'https://example.com'.
const Koa = require('koa');
const cors = require('@koa/cors');
const app = new Koa();
app.use(cors({ origin: 'https://example.com' }));
app.listen(3000);
Configuring Additional CORS Options
This code demonstrates how to configure additional CORS options such as allowed methods, headers, exposed headers, max age, and credentials.
const Koa = require('koa');
const cors = require('@koa/cors');
const app = new Koa();
app.use(cors({
origin: '*',
allowMethods: ['GET', 'POST'],
allowHeaders: ['Content-Type', 'Authorization'],
exposeHeaders: ['Content-Length', 'Date'],
maxAge: 3600,
credentials: true
}));
app.listen(3000);