- 生产前后端同源(/api),浏览器不再触发跨域;默认只放行本地开发 localhost:5173 - 移除 api.oms.gztbyc.com 相关默认来源(该域名已退役),仍需跨域时用 CORS_ORIGINS 覆盖 - 同步更新 cors 中间件注释与 env.production.example 说明 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
54 lines
2.2 KiB
JavaScript
54 lines
2.2 KiB
JavaScript
'use strict';
|
||
|
||
/**
|
||
* 跨域(CORS)中间件
|
||
*
|
||
* 生产环境前端与后端同源(https://oms.gztbyc.com/api),浏览器不会发预检;
|
||
* 只有本地开发(vite dev server)或直连后端地址调试时,浏览器才会对带 Authorization 头的请求
|
||
* 先发 OPTIONS 预检,并要求响应带 Access-Control-Allow-Origin,否则请求会被浏览器直接拦截。
|
||
*
|
||
* 白名单来自 config.cors.origins(可用环境变量 CORS_ORIGINS 覆盖,逗号分隔;'*' 表示不限制来源)。
|
||
* 本服务用 Bearer Token 鉴权、不使用 Cookie,故不返回 Access-Control-Allow-Credentials。
|
||
*
|
||
* @param {Object} options 配置项(config.cors)
|
||
* @param {Array<String>} [options.origins] 允许跨域访问的来源白名单
|
||
* @param {Array<String>} [options.headers] 允许的请求头
|
||
* @param {String} [options.methods] 允许的请求方法
|
||
* @param {Number} [options.maxAge] 预检结果缓存秒数
|
||
* @param {Egg.Application} app egg 应用实例
|
||
* @return {Function} egg 中间件
|
||
*/
|
||
module.exports = (options = {}, app) => {
|
||
const origins = (options.origins || [])
|
||
.map(item => String(item).trim().replace(/\/+$/, ''))
|
||
.filter(Boolean);
|
||
const allowAll = origins.includes('*');
|
||
const allowHeaders = (options.headers || [ 'Content-Type', 'Authorization', 'X-Requested-With' ]).join(', ');
|
||
const allowMethods = options.methods || 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS';
|
||
const maxAge = String(options.maxAge || 86400);
|
||
|
||
if (!origins.length) {
|
||
app.logger.warn('[cors] config.cors.origins 为空,跨域请求将全部被浏览器拦截');
|
||
}
|
||
|
||
return async function cors(ctx, next) {
|
||
const origin = ctx.get('Origin');
|
||
|
||
if (origin && (allowAll || origins.includes(origin.replace(/\/+$/, '')))) {
|
||
ctx.set('Access-Control-Allow-Origin', origin);
|
||
ctx.set('Access-Control-Allow-Methods', allowMethods);
|
||
ctx.set('Access-Control-Allow-Headers', allowHeaders);
|
||
ctx.set('Access-Control-Max-Age', maxAge);
|
||
ctx.append('Vary', 'Origin');
|
||
}
|
||
|
||
// 预检请求直接返回 204,不进入路由(egg 路由不注册 OPTIONS)
|
||
if (ctx.method === 'OPTIONS') {
|
||
ctx.status = 204;
|
||
return;
|
||
}
|
||
|
||
await next();
|
||
};
|
||
};
|