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

Ajax请求Spring Controller触发strict-origin-when-cross-origin跨域拦截如何解决

跨域问题解决步骤

问题根因说明

你现有方案不生效首先有两个底层问题:

  1. Controller接口要求必填@RequestParam Integer id参数,但前端AJAX请求未携带任何参数,Spring会先返回400错误,该错误响应不会携带你配置的跨域头,浏览器会优先判定为跨域拦截。
  2. 零散配置跨域头容易被Spring拦截器、异常处理器覆盖,导致配置不生效。

修复步骤

1. 补全前端请求参数

修改AJAX请求,携带必填的id参数:

function move(moveDir,velocity){
    $.ajax({
        type : "POST",
        url : getContextPath()  + "/event",
        // 新增参数,替换为实际业务的id值
        data: {
            id: 1
        },
        success: function(data){
            console.log(data)
        },
        // 新增错误回调方便排查问题
        error: function(err){
            console.error("请求错误:", err)
        }
    });
}

2. 替换为Spring全局跨域配置

删除Controller中手动设置的response.setHeader("Access-Control-Allow-Origin", "*")语句,以及Controller类上的@CrossOrigin注解,新增全局跨域配置类:

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                // 本地调试可设为*,生产环境替换为实际前端域名
                .allowedOrigins("*")
                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
                .allowedHeaders("*")
                .maxAge(3600)
                // 当allowedOrigins设为*时,allowCredentials必须设为false
                .allowCredentials(false);
    }
}

3. 额外排查点

  • 确认前端访问地址与跨域允许的源一致,比如如果前端是用127.0.0.1:8081访问,配置写localhost:8081也会不生效。
  • 打开浏览器控制台网络面板,查看请求状态码,如果是400/404先处理地址、参数错误,再验证跨域配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 15:54:09