前后端分离的项目:Vue + SpringBoot
前提:前后端的跨域问题已解决,前后端接口联调正常
问题:在过滤器Filter
类中,验证token或验证入参,错误则返回相应的错误信息给前端
使用Postman测试均正常
但是前端请求一直会报以下问题
Access to XMLHttpRequest at 'http://192.168.0.157:8080/user/internal/getUserInfo' from
origin 'http://192.168.0.146:8070' has been blocked by CORS policy: The value of the
'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when
the request's credentials mode is 'include'. The credentials mode of requests initiated
by the XMLHttpRequest is controlled by the withCredentials attribute.
翻译翻译:
‘访问XMLHttpRequest’http://192.168.0.157:8080/questionDatabase/internal/countByCatalogAndQuestionType?catalogId=&questionType=4&examType=0“从原点”http://192.168.0.146:8070’已被CORS策略阻止:响应中的’Access-Control-Allow-Origin’头的值在请求被阻止时不能是通配符’*'凭据模式为“包含”。XMLHttpRequest发起的请求的凭据模式由withCredentials属性控制。
问题原因:
响应头response
中设置Access-Control-Allow-Origin
没有设置或者设置错误
原来的代码
if (StringUtils.isEmpty(parameter)){
JSONObject jsonObject = new JSONObject();
//这个地方是定义缺少参数或者参数为空的时候返回的数据
jsonObject.put("status", 203);
jsonObject.put("msg", "接口参数中缺少必要的"+s+"值");
response.setHeader("Content-type", "application/json;charset=UTF-8");
//跨域
response.setHeader("Access-Control-Allow-Origin", "*");//这里设置为*,所以报了跨域问题
response.getWriter().write(jsonObject.toJSONString());
log.error("***接口请求参数不足***");
return false;
}
针对这个问题
解决方案如下:
将Access-Control-Allow-Origin
设置为发起请求的对应IP和端口,可以从请求头中获取
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
后来
又
发现个错
Access to XMLHttpRequest at 'http://192.168.0.157:8080/login' from origin
'http://192.168.0.146:8070' has been blocked by CORS policy: The value of the 'Access-
Control-Allow-Credentials' header in the response is '' which must be 'true' when the
request's credentials mode is 'include'. The credentials mode of requests initiated by
the XMLHttpRequest is controlled by the withCredentials attribute.
部分翻译:
响应中“Access Control Allow Credentials”标头的值为“”,当请求的凭据模式为“include”时,该值必须为“true”。XMLHttpRequest发起的请求的凭据模式由withCredentials属性控制
针对这个问题
解决方案如下:
response.setHeader("Access-Control-Allow-Credentials", "true");