ajax跨域请求中设置header的一个坑

今天晚上有同事反馈,线上一个登记系统出现错误

提示的报错内容为:

1
2
3
4
5
6
{
"readyState": 0,
"responseText": "",
"status": 0,
"statusText": "error"
}

第一眼直觉就是ajax跨域请求失败了,触发了CORS限制。

印象中自己已经做好了跨域相关的配置呀,怎么还会触发呢?

由于是在微信浏览器上才会出现,使用vconsole也没有找到详细的错误原因,又粗略检查了下代码,java后端代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
// 工具类中的统一返回
httpResponse.addHeader("Access-Control-Allow-Origin", "*");
httpResponse.addHeader("Access-Control-Allow-Headers", "*");
httpResponse.addHeader("Access-Control-Allow-Credentials", "true");
httpResponse.addHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
httpResponse.addHeader("Access-Control-Max-Age", "3600");

//继承WebMvcConfigurationSupport的configurer
registry.addMapping("/**")// 设置允许跨域的路径
.allowedOrigins("*")// 设置允许跨域请求的域名
.allowCredentials(true)// 是否允许证书 不再默认开启
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")// 设置允许的方法
.allowedHeaders("*")

origin和method都已经配置上了需要配置的header,可是微信浏览器的options预校验死活不通过!

最终,将目光锁定在了Access-Control-Allow-Headers参数上

查阅资料后发现,Access-Control-Allow-Headers请求头的值设置成 “*” 是不生效的,只能设置成具体的值,比如token等等
image.png
最终代码修改如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
// 工具类中的统一返回
httpResponse.addHeader("Access-Control-Allow-Origin", "*");
httpResponse.addHeader("Access-Control-Allow-Headers", "X-Token");
httpResponse.addHeader("Access-Control-Allow-Credentials", "true");
httpResponse.addHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
httpResponse.addHeader("Access-Control-Max-Age", "3600");

//继承WebMvcConfigurationSupport的configurer
registry.addMapping("/**")// 设置允许跨域的路径
.allowedOrigins("*")// 设置允许跨域请求的域名
.allowCredentials(true)// 是否允许证书 不再默认开启
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")// 设置允许的方法
.allowedHeaders("X-Token")

指定明确的Access-Control-Allow-Headers请求头的值即可

ajax跨域请求中设置header的一个坑

https://www.stonewu.com/post/cors-ajax-bug.html

作者

StoneWu

发布于

2020-02-28

更新于

2023-03-22

许可协议

评论