From cecc04e60e5837423235d75bd2a1204565d6452f Mon Sep 17 00:00:00 2001 From: IamFurina Date: Thu, 17 Jul 2025 10:56:27 +0800 Subject: [PATCH] =?UTF-8?q?fix(cors):=20=E4=BF=AE=E5=A4=8D=E6=97=A0?= =?UTF-8?q?=E6=B3=95=E6=90=BA=E5=B8=A6cookie=E8=AF=B7=E6=B1=82=E7=9A=84cor?= =?UTF-8?q?s=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env | 3 ++- server.js | 8 +++++++- vercel.json | 7 ++++++- 3 files changed, 15 insertions(+), 3 deletions(-) diff --git a/.env b/.env index 278d8c0..b977252 100644 --- a/.env +++ b/.env @@ -1,5 +1,6 @@ # CORS资源共享设置 -CORS_ALLOW_ORIGIN = "*" +## 如果你需要配置, 请取消下面的注释并设置具体的域名 +# CORS_ALLOW_ORIGIN = "*" ### UnblockNeteaseMusic 设置项 ## 启用全局解灰, 无论是否调用参数都会使用解灰(推荐开启) diff --git a/server.js b/server.js index 24c9662..1fd9aff 100644 --- a/server.js +++ b/server.js @@ -145,10 +145,16 @@ async function consturctServer(moduleDefs) { * CORS & Preflight request */ app.use((req, res, next) => { + // 强制设置 Access-Control-Allow-Credentials: true if (req.path !== '/' && !req.path.includes('.')) { + let allowOrigin = CORS_ALLOW_ORIGIN || req.headers.origin + // 禁止为 *,必须为具体域名 + if (!allowOrigin || allowOrigin === '*') { + allowOrigin = req.headers.origin || '' + } res.set({ 'Access-Control-Allow-Credentials': true, - 'Access-Control-Allow-Origin': CORS_ALLOW_ORIGIN || req.headers.origin || '*', + 'Access-Control-Allow-Origin': allowOrigin, 'Access-Control-Allow-Headers': 'X-Requested-With,Content-Type', 'Access-Control-Allow-Methods': 'PUT,POST,GET,DELETE,OPTIONS', 'Content-Type': 'application/json; charset=utf-8', diff --git a/vercel.json b/vercel.json index e8eaad7..d0a6bf7 100644 --- a/vercel.json +++ b/vercel.json @@ -9,7 +9,12 @@ "routes": [ { "src": "/(.*)", - "dest": "/" + "dest": "/", + "headers": { + "Access-Control-Allow-Credentials": "true", + "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS", + "Access-Control-Allow-Headers": "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" + } } ] }