如果在base.js 中设置跨域,如果请求在Logic这里效验不通过,前台就会报跨域错误。
最佳方案是在中间件里面设置跨域。
第一步
在config 的中间件配置里面,启用一个自定义中间件,这个可以是你的模块名称什么的,然后设置下仅在访问模块的方法的时候生效,一般前后端分离是写后台界面时候产生,所以我这里设置admin。
{
handle: 'admin',
match: ctx => {
const url = ctx.path;
if (url.slice(0, 6).toLowerCase() === '/admin') {
console.log("调用admin中间件");
return true;
}
return false;
},
options: {
}
},
第二步
创建跨域处理的js,
如果没有origin头部表示并非跨域,就直接next。
如果存在,就设置跨域头部,
然后再判断是否options请求,如果不是就next,让它进入控制器中,
如果是options请求就设置状态码为204。
module.exports = (options, app) => {
return (ctx, next) => {
const requestOrigin = ctx.get('Origin');
if (!requestOrigin) {
console.log('非跨域连接')
return next();
}
console.log('跨域连接')
ctx.set('Access-Control-Allow-Origin', requestOrigin || "*");
ctx.set('Access-Control-Allow-Methods', 'POST,GET,OPTIONS');
ctx.set('Access-Control-Allow-Credentials', true);
ctx.set('Access-Control-Max-Age', 3600);
ctx.set('Access-Control-Allow-Headers', 'Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With');
if (ctx.method !== 'OPTIONS'){
return next();
}
ctx.status = 204;
console.log('options请求')
}
}