后端产生的CORS跨域问题

前后端分离的项目: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");
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值