
本文详解如何在 Spring Boot(集成 Spring Security)与 Next.js 构建的全栈应用中,正确处理 CORS 错误——尤其针对预检请求失败、响应头缺失 Access-Control-Allow-Origin 的典型问题,并推荐更优的开发期代理方案。
本文详解如何在 spring boot(集成 spring security)与 next.js 构建的全栈应用中,正确处理 cors 错误——尤其针对预检请求失败、响应头缺失 `access-control-allow-origin` 的典型问题,并推荐更优的开发期代理方案。
在本地开发中,当 Next.js 前端(http://localhost:3000)调用 Spring Boot 后端(http://localhost:8081)API 时,浏览器会因同源策略触发 CORS 预检(OPTIONS 请求)。若后端未正确响应预检请求(如缺少 Access-Control-Allow-Origin、Access-Control-Allow-Methods 等关键头),就会报出如下经典错误:
Access to XMLHttpRequest at 'http://localhost:8081/api/v1/auth/login' from origin 'http://localhost:3000/' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
你当前的配置存在两个关键问题:
-
Spring Security 的
CorsConfigurationSource未生效:虽然定义了@Bean CorsConfigurationSource,但 Spring Security 默认不会自动使用它,除非显式启用 CORS 支持; -
WebMvcConfigurer与 Spring Security 的 CORS 配置冲突:WebMvcConfigurer#addCorsMappings仅作用于 Spring MVC 层,而 Spring Security 的过滤器链(如SecurityFilterChain)会拦截并优先处理请求;若未在 Security 配置中启用 CORS,MVC 层的 CORS 映射将被跳过。
✅ 正确做法是:在 HttpSecurity 中显式启用 CORS,并关联你的 CorsConfigurationSource Bean。修改 SecurityConfig 如下:
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.cors(cors -> cors.configurationSource(corsConfigurationSource())) // ? 关键:启用并指定配置源
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(authorize -> authorize
.requestMatchers("/api/v1/auth/register", "/api/v1/auth/login")
.permitAll()
.anyRequest()
.authenticated()
)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authenticationProvider(authenticationProvider)
.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);
return http.build();
}
同时,移除 KeeperApplication 中重复且低效的 WebMvcConfigurer Bean(尤其避免使用 allowedOrigins("*") 在生产环境):
// ❌ 删除此 Bean —— 它在 Security 拦截后不生效,且 `*` 不支持凭据(如 cookies)
/*
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("*")
.allowedHeaders("*");
}
};
}
*/
⚠️ 注意事项:
-
allowedOrigins("*")无法与withCredentials: true(如携带 Cookie 或 Authorization 头)共存,应明确指定来源(如"http://localhost:3000"); - 生产环境务必限制
allowedOrigins,禁止通配符; - 若前端需发送认证凭据(如 JWT 存于 Cookie),需额外配置:
configuration.setAllowCredentials(true); // 在 CorsConfiguration 中设置
然而,更推荐的开发实践是彻底规避 CORS —— 使用 Next.js 内置的 Rewrites 功能进行服务端代理。这不仅绕过浏览器 CORS 限制,还能统一 API 基础路径、提升调试体验,且无需后端任何 CORS 配置。
DMap GL地图JSAPI(dmapgl)开发指南。用于编写、审查、调试 DMap 地图 API 代码,涵盖地图初始化、覆盖物渲染、图层管理、事件处理、控件交互等任务。当用户提及 dmap、dmapgl、jsapi‑gl 或相关地图开发需求时自动触发。
在项目根目录 next.config.js 中添加重写规则:
/** @type {import('next').NextConfig} */
module.exports = {
async rewrites() {
return [
{
source: '/api/:path*', // 匹配所有 /api/ 开头的请求
destination: 'http://localhost:8081/:path*' // 代理到 Spring Boot
}
];
}
};
配置后,前端可直接发起相对路径请求:
// Next.js 页面中
const res = await fetch('/api/v1/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password })
});
该请求实际由 Next.js Dev Server 转发至 http://localhost:8081/api/v1/auth/login,完全同源(都是 http://localhost:3000 发起),彻底消除 CORS 干扰。
✅ 总结:
- 临时调试可修复 Spring Security 的 CORS 配置(启用
cors()并绑定configurationSource); - 长期开发与最佳实践,请优先采用 Next.js Rewrites 代理,安全、简洁、符合现代全栈协作范式;
- 生产部署时,应通过 Nginx 或云网关统一路由和跨域策略,而非依赖应用层 CORS。










