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

Spring Boot + Nuxt.js 跨域CORS错误解决方案咨询

解决CORS错误的具体方案

问题核心

你的请求调用/api/demo/signup后被后端重定向到/login,但/login端点未配置CORS允许http://localhost:3001访问,导致浏览器拦截。同时当前配置存在几处细节错误,以下是针对性修复步骤:


1. 修正Nuxt的axios配置拼写错误

axios配置里的credenitals是拼写错误,会影响跨域凭证携带功能,修正为:

axios: {
  proxy: true,
  debug: true,
  credentials: true, // 修正拼写错误
  retry: { retries: 3 },
},

2. 统一Spring后端的CORS全局配置

移除Controller上的@CrossOrigin注解,改用全局过滤器覆盖所有端点(包括/login),避免Spring Security拦截导致CORS配置失效:

@Bean
public CorsFilter corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("http://localhost:3001");
    config.addAllowedHeader("*");
    config.addAllowedMethod("*");
    source.registerCorsConfiguration("/**", config);
    return new CorsFilter(source);
}

(替换原有的WebMvcConfigurer方式,Spring Security环境下过滤器优先级更高)

3. 修复后端重定向根源

/api/demo/signup重定向到/login,大概率是Spring Security拦截了匿名请求。若注册接口允许匿名访问,需在Security配置中放行:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and()
            .authorizeRequests()
            .antMatchers("/api/demo/signup").permitAll() // 放行注册接口
            .anyRequest().authenticated();
    }
}

(若之前注释掉了SecurityAutoConfiguration,需确保该配置类生效)

4. 修正前端请求参数传递

前端axios.post写法错误,参数嵌套在params对象里会导致后端无法正确接收,同时避免混用async/await与.then/.catch:

async save(){
  console.log('data chk', this.data)
  try {
    const result = await axios.post('/api/demo/signup', this.data)
    console.log('result', result)
  } catch (err) {
    console.error(err)
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 22:05:22