今天晚上有同事反馈,线上一个登记系统出现错误
提示的报错内容为:
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");
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");
registry.addMapping("/**") .allowedOrigins("*") .allowCredentials(true) .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") .allowedHeaders("X-Token")
|
指定明确的Access-Control-Allow-Headers请求头的值即可