const Koa= require('koa');
const router = require('koa-router')();
const parser = require('koa-parser');
var app = new Koa();
app.use(parser())
// 实现跨域
app.use(async (ctx, next)=> {
ctx.set('Access-Control-Allow-Origin', 'http://localhost:8080');
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');
console.log(ctx.method)
if (ctx.method === 'OPTIONS') {
ctx.body = 200;
} else {
await next();
}
});
app.use(router.routes());
app.listen(3000,()=>{
console.log('server is running')
})
一般axios会先通过options进行判断是否可以跨域,可以跨域之后才会访问我们的请求,所以这里服务器输出了options+put两个