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

使用jQuery调用REST API遇CORS问题,请求排查修复

跨域问题排查与修复方案

问题背景

直接在Chrome中访问http://localhost:8080/api/languages/getall可正常返回结果[{"id":1,"name":"c"},{"id":2,"name":"java"}],但使用jQuery代码调用该REST接口时触发CORS错误,报错信息:

  • 'from origin 'null' has been blocked by CORS policy'
  • GET http://localhost:8080/api/languages/getall net::ERR_FAILED

Spring后端接口已添加@CrossOrigin(origins = "http://localhost:8080")注解,且React代码可正常调用该接口。

根源分析

1. 静态页面的源为null

你是直接本地打开HTML文件(通过file://协议),此时页面的源被浏览器标记为null,而Spring后端的@CrossOrigin仅允许http://localhost:8080的请求来源,因此被拦截。

React代码能正常调用的原因:React项目通常运行在独立端口(如http://localhost:3000),要么你配置了代理将请求转发到8080(避免跨域),要么后端实际允许了该端口的跨域请求。

2. jQuery请求的错误配置

你的jQuery代码存在多处无效配置:

  • 不存在CORS: true这个参数,属于无效设置
  • Access-Control-Allow-Origin是服务器返回给浏览器的响应头,前端请求时添加该头完全无效,反而可能干扰请求
  • contentType:'application/json'对GET请求无意义,GET请求无需设置该字段

修复方案

方案一:让HTML页面运行在允许的源下

这是推荐的规范做法:

  • 将HTML文件放到Spring项目的static目录下,通过http://localhost:8080/你的页面.html访问,此时页面与接口同源,不会触发跨域检查
  • 用本地服务器打开HTML文件,比如执行python -m http.server 8080(Python3环境),然后访问http://localhost:8080/你的页面.html,此时源为http://localhost:8080,符合后端跨域配置

方案二:调整后端跨域配置(临时测试用)

如果只是临时测试,可以修改Spring的@CrossOrigin注解,允许null源或所有源:

// 允许所有源,生产环境谨慎使用
@CrossOrigin(origins = "*")
@GetMapping("/languages/getall")
List<GetLanguageResponse> getAllResponse(){
  return languagesService.getAllResponse();
}

或者仅允许null源和原有的http://localhost:8080:

@CrossOrigin(origins = {"http://localhost:8080", "null"})
@GetMapping("/languages/getall")
List<GetLanguageResponse> getAllResponse(){
  return languagesService.getAllResponse();
}

方案三:修正jQuery请求代码

无论采用哪种方案,都需要修复jQuery的错误配置,正确代码如下:

$.ajax({
    url: "http://localhost:8080/api/languages/getall",
    type: 'GET',
    dataType: 'json',
    success: function (data){
        console.log(data);
    },
    error: function(xhr, status, error) {
        console.error('请求失败:', error);
    }
});
  • 移除无效的CORS: true参数
  • 删除前端不该设置的Access-Control-Allow-Origin请求头
  • 去掉GET请求不需要的contentType:'application/json'
  • 增加错误回调,方便排查后续问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 16:10:31