fix(cors): 修复无法携带cookie请求的cors问题

This commit is contained in:
IamFurina 2025-07-17 10:56:27 +08:00 committed by ImFurina
parent 34da6ddd6c
commit cecc04e60e
3 changed files with 15 additions and 3 deletions

3
.env
View File

@ -1,5 +1,6 @@
# CORS资源共享设置 # CORS资源共享设置
CORS_ALLOW_ORIGIN = "*" ## 如果你需要配置, 请取消下面的注释并设置具体的域名
# CORS_ALLOW_ORIGIN = "*"
### UnblockNeteaseMusic 设置项 ### UnblockNeteaseMusic 设置项
## 启用全局解灰, 无论是否调用参数都会使用解灰(推荐开启) ## 启用全局解灰, 无论是否调用参数都会使用解灰(推荐开启)

View File

@ -145,10 +145,16 @@ async function consturctServer(moduleDefs) {
* CORS & Preflight request * CORS & Preflight request
*/ */
app.use((req, res, next) => { app.use((req, res, next) => {
// 强制设置 Access-Control-Allow-Credentials: true
if (req.path !== '/' && !req.path.includes('.')) { if (req.path !== '/' && !req.path.includes('.')) {
let allowOrigin = CORS_ALLOW_ORIGIN || req.headers.origin
// 禁止为 *,必须为具体域名
if (!allowOrigin || allowOrigin === '*') {
allowOrigin = req.headers.origin || ''
}
res.set({ res.set({
'Access-Control-Allow-Credentials': true, '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-Headers': 'X-Requested-With,Content-Type',
'Access-Control-Allow-Methods': 'PUT,POST,GET,DELETE,OPTIONS', 'Access-Control-Allow-Methods': 'PUT,POST,GET,DELETE,OPTIONS',
'Content-Type': 'application/json; charset=utf-8', 'Content-Type': 'application/json; charset=utf-8',

View File

@ -9,7 +9,12 @@
"routes": [ "routes": [
{ {
"src": "/(.*)", "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"
}
} }
] ]
} }