- 删除 miniprogram/ 整个工程(28 个跟踪文件:uni-app 页面、接口封装、构建配置) - README 去掉小程序目录、7304 端口、进度条目与用法链接 - cors 中间件与 CORS_ORIGINS 示例注释不再以「小程序 H5 预览」举例 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
54 lines
1.9 KiB
JavaScript
54 lines
1.9 KiB
JavaScript
'use strict';
|
||
|
||
/**
|
||
* 跨域(CORS)
|
||
*
|
||
* 为什么需要:前端 SPA 用浏览器发起请求,接口走后端绝对地址(不经 Vite 同源代理)时需要 CORS;
|
||
* 桌面端 / 安卓端 / 扩展走的是原生请求,不受同源策略限制,这段对它们没有影响。
|
||
*
|
||
* 配置(`config.cors`):
|
||
* - `origins`: `'*'`(默认)或逗号分隔白名单(env `CORS_ORIGINS`),白名单外返回不带 CORS 头;
|
||
* - `enable: false` 可整体关闭。
|
||
*
|
||
* 说明:鉴权只用 header 里的令牌(Authorization / X-Subject-Id),**不依赖 cookie**,
|
||
* 所以不需要 `Access-Control-Allow-Credentials`。
|
||
*/
|
||
module.exports = () => {
|
||
return async function cors(ctx, next) {
|
||
const cfg = ctx.app.config.cors || {};
|
||
|
||
if (cfg.enable !== false) {
|
||
const origin = ctx.get('origin');
|
||
const allowed = pickOrigin(origin, cfg.origins);
|
||
|
||
if (allowed) {
|
||
ctx.set('Access-Control-Allow-Origin', allowed);
|
||
ctx.set('Vary', 'Origin');
|
||
ctx.set('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS');
|
||
ctx.set(
|
||
'Access-Control-Allow-Headers',
|
||
'Authorization,Content-Type,X-Subject-Id,X-Access-Token,X-Internal-Token,X-Scanner-Token,X-Pay-Sign',
|
||
);
|
||
ctx.set('Access-Control-Max-Age', '86400');
|
||
ctx.set('Access-Control-Expose-Headers', 'Content-Disposition');
|
||
}
|
||
}
|
||
|
||
// 预检请求直接结束(后续路由没有 OPTIONS,否则会 404 让浏览器判成跨域失败)
|
||
if (ctx.method === 'OPTIONS') {
|
||
ctx.status = 204;
|
||
return;
|
||
}
|
||
|
||
await next();
|
||
};
|
||
};
|
||
|
||
/** 命中白名单返回要回填的 Origin;`*` 时回显实际 Origin(没有 Origin 就不加头) */
|
||
function pickOrigin(origin, origins) {
|
||
if (!origin) return '';
|
||
const list = Array.isArray(origins) ? origins : [];
|
||
if (list.includes('*')) return '*';
|
||
return list.includes(origin) ? origin : '';
|
||
}
|