You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js 14调用SpringBoot接口遇CORS错误的解决方法

解决Next.js 14调用SpringBoot后端的CORS问题

问题根源

你在next.config.mjs中配置的CORS headers仅对Next.js自身的/api路由生效,但你是直接从前端页面调用外部SpringBoot后端接口,这套配置完全不适用。Postman不受浏览器同源策略限制,所以能正常请求,而浏览器会拦截跨域请求触发CORS错误。


解决方案一:在SpringBoot后端配置CORS

直接在后端开放允许跨域的权限,有两种方式:

1. 全局CORS配置

添加一个配置类,统一处理所有接口的跨域请求:

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() {
        CorsConfiguration config = new CorsConfiguration();
        // 替换为你的Next.js前端实际域名(生产环境不要用*)
        config.addAllowedOrigin("http://localhost:3000");
        config.setAllowCredentials(true);
        config.addAllowedMethod("*"); // 允许所有HTTP方法
        config.addAllowedHeader("*"); // 允许所有请求头

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config); // 对所有接口生效
        return new CorsFilter(source);
    }
}

2. 单个接口配置

如果只想开放特定接口的跨域权限,直接在接口方法上添加注解:

@CrossOrigin(origins = "http://localhost:3000", allowCredentials = "true")
@GetMapping("/your-api-path")
public ResponseEntity<?> yourApiMethod() {
    // 接口逻辑
}

解决方案二:在Next.js中配置反向代理(推荐生产环境)

通过Next.js的反向代理,让前端请求先发送到同域的Next.js服务器,再由服务器转发到SpringBoot后端,从根源避免跨域问题:

修改next.config.mjs,添加rewrites配置:

const nextConfig = {
  async rewrites() {
    return [
      {
        source: "/api/:path*",
        // 替换为你的SpringBoot后端实际地址(比如http://localhost:8080)
        destination: "http://your-springboot-server:port/:path*",
      },
    ];
  },
  experimental: {
    optimizePackageImports: ['@mantine/core', '@mantine/hooks'],
  },
};

export default nextConfig;

注意事项

  • 前端axios请求时,将目标地址改为/api/xxx(比如原请求是http://localhost:8080/user,现在改为/api/user)
  • 之前配置的headers规则可以直接删除,因为代理模式下不需要前端处理跨域
  • 生产环境部署时,确保后端地址配置正确,若后端有认证机制,需确保代理转发时携带必要的请求头(比如Cookie、Authorization)

内容的提问来源于stack exchange,提问作者Suneth Udayanaga

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 08:07:20