1. Add a middleware

app.use(async (ctx, next)=> {
  ctx.set('Access-Control-Allow-Origin'.The '*');
  ctx.set('Access-Control-Allow-Headers'.'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
  ctx.set('Access-Control-Allow-Methods'.'PUT, POST, GET, DELETE, OPTIONS');
  if (ctx.method == 'OPTIONS') {
    ctx.body = 200; 
  } else {
    awaitnext(); }});Copy the code

2. Usekoa2-cors

2.1 to download
npm install koa2-cors --save
Copy the code

2.2 the use of

const Koa = require('koa');
const cors = require('koa2-cors');
const app = new Koa();

app.use(cors());
/ / or
app.use(
    cors({
        origin: function(ctx) { // Set requests from the specified domain to be allowed
            if (ctx.url === '/test') {
                return The '*'; // Allow requests from all domain names
            }
            return 'http://localhost:8080'; // only requests for http://localhost:8080 are allowed
        },
        maxAge: 5.// Specifies the validity period of this precheck request, in seconds.
        credentials: true.// Whether cookies can be sent
        allowMethods: ['GET'.'POST'.'PUT'.'DELETE'.'OPTIONS'].// Sets the allowed HTTP request methods
        allowHeaders: ['Content-Type'.'Authorization'.'Accept'].// Set all header fields supported by the server
        exposeHeaders: ['WWW-Authenticate'.'Server-Authorization'] // Set to get additional custom fields}));Copy the code

Reference Link 1

Reference Link 2

Reference Link 3