From 8ff41d907df12500f3e11456bf763ad2853518d2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9F=B3=E6=B8=85=E7=88=BD?= Date: Fri, 25 Apr 2025 10:32:01 +0800 Subject: [PATCH] =?UTF-8?q?=E8=B6=85=E7=AE=A1=E5=90=8E=E5=8F=B0=20-=20?= =?UTF-8?q?=E5=89=8D=E7=AB=AF=E5=A2=9E=E5=8A=A0=E8=B7=A8=E5=9F=9F=E6=94=AF?= =?UTF-8?q?=E6=8C=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- SuperAdmin/middleware.ts | 31 +++++++++++++++++++++++++++++++ SuperAdmin/next.config.mjs | 13 +++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 SuperAdmin/middleware.ts diff --git a/SuperAdmin/middleware.ts b/SuperAdmin/middleware.ts new file mode 100644 index 00000000..ae1ba39c --- /dev/null +++ b/SuperAdmin/middleware.ts @@ -0,0 +1,31 @@ +import { NextResponse } from 'next/server' +import type { NextRequest } from 'next/server' + +export function middleware(request: NextRequest) { + // 获取响应对象 + const response = NextResponse.next() + + // 设置CORS头 + response.headers.set('Access-Control-Allow-Credentials', 'true') + response.headers.set('Access-Control-Allow-Origin', '*') // 在生产环境中应该设置为特定域名 + response.headers.set('Access-Control-Allow-Methods', 'GET,DELETE,PATCH,POST,PUT,OPTIONS') + response.headers.set('Access-Control-Allow-Headers', 'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version, Authorization') + + // 处理预检请求 + if (request.method === 'OPTIONS') { + return new NextResponse(null, { status: 200, headers: response.headers }) + } + + return response +} + +// 配置中间件应用的路径 +export const config = { + matcher: [ + // 匹配所有API路由 + '/api/:path*', + // 匹配需要跨域的特定外部API请求 + '/company/:path*', + '/v1/api/:path*', + ], +} \ No newline at end of file diff --git a/SuperAdmin/next.config.mjs b/SuperAdmin/next.config.mjs index db42585b..aa8e7997 100644 --- a/SuperAdmin/next.config.mjs +++ b/SuperAdmin/next.config.mjs @@ -27,6 +27,19 @@ const nextConfig = { parallelServerBuildTraces: true, parallelServerCompiles: true, }, + async headers() { + return [ + { + source: '/api/:path*', + headers: [ + { key: 'Access-Control-Allow-Credentials', value: 'true' }, + { key: 'Access-Control-Allow-Origin', value: '*' }, + { key: 'Access-Control-Allow-Methods', value: 'GET,DELETE,PATCH,POST,PUT,OPTIONS' }, + { key: 'Access-Control-Allow-Headers', value: 'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version, Authorization' }, + ], + }, + ] + }, } if (userConfig) {