anchundan
Version:
40 lines • 1.42 kB
JavaScript
let allowList =null;
const getAllowList=(config)=>{
if(!config) return;
//let {domains} = config;
let domains = config.domains || config.origins || null;
if(!domains) return;
if(allowList) return allowList;
allowList = {};
domains.forEach(item=>{
allowList[item] = 1;
});
return allowList;
};
module.exports =(config)=>{
if(!config){
return async (ctx,next)=>{
await next();
};
}
getAllowList(config);
return async (ctx,next)=>{
let host = ctx.request.header.origin;
if(allowList['*']){
host = '*';
}
const {headers,methods,credentials} = config;
if(allowList[host] === 1){
ctx.set('Access-Control-Allow-Origin',host);
ctx.set('Access-Control-Expose-Headers',"Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma,FooBar");
if(headers) {
ctx.set('Access-Control-Allow-Headers',headers);
}
ctx.set('Access-Control-Allow-Methods', ( methods && (methods instanceof Array)) ? methods.join(',') : methods || 'DELETE,PUT,POST,GET,OPTIONS');
if(credentials && credentials == true){
ctx.set('Access-Control-Allow-Credentials','true');
}
}
await next();
};
};