NextJS调用Spring Boot接口失败:仅同热点可访问,代码请求无响应
解决NextJS请求Spring Boot跨域接口失败问题
问题根源
浏览器的同源策略会限制不同源的前端页面直接请求后端接口,而Postman或浏览器直接访问URL不受该策略约束。你的场景中,NextJS应用的源(比如http://localhost:3000)与后端接口的源(同事电脑IP+端口)属于不同源,触发了CORS校验失败,导致请求被浏览器拦截。
解决方案
1. 后端Spring Boot配置CORS(推荐方案)
在Spring Boot中添加全局CORS配置,允许你的NextJS应用所在源访问接口:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; @Configuration public class CorsConfig { @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); // 生产环境建议指定具体NextJS地址,比如http://你的电脑IP:3000,*代表允许所有源 config.addAllowedOriginPattern("*"); // 允许所有HTTP请求方法 config.addAllowedMethod("*"); // 允许所有请求头 config.addAllowedHeader("*"); // 如需携带Cookie,开启此配置 config.setAllowCredentials(true); // 对所有接口生效 source.registerCorsConfiguration("/**", config); return new CorsFilter(source); } }
也可以在单个Controller类上添加注解快速生效:@CrossOrigin(origins = "*", allowCredentials = "true")
2. 前端NextJS配置代理(临时方案)
如果后端暂时无法修改,可通过NextJS代理转发请求绕过CORS限制:
在项目根目录创建next.config.js文件,添加代理规则:
/** @type {import('next').NextConfig} */ const nextConfig = { async rewrites() { return [ { source: '/api/:path*', destination: 'http://同事电脑IP:后端端口/:path*', // 替换为实际后端地址 }, ] }, } module.exports = nextConfig
修改请求代码,将目标地址改为本地代理路径:
// 原请求:fetch('http://同事IP:端口/api/data') // 修改后: fetch('/api/data') .then(res => res.json()) .then(data => console.log(data))
3. 检查防火墙设置
确认同事电脑的防火墙允许后端端口的入站请求,部分防火墙会拦截OPTIONS预检请求(CORS校验必需),需放开对应端口的所有TCP请求权限。
内容的提问来源于stack exchange,提问作者th-mhmn
相关产品推荐
相关产品推荐

