JAVA拦截器,JAVA返回结果跨域问题解决-has been blocked by CORS policy

JAVA拦截器,JAVA返回结果跨域问题解决-has been blocked by CORS policy

遇到的问题:

通过拦截器做权限控制,没有权限时返回了json值,结果前端请求时提示跨域了

备注:我的前端站点和后端站点不是一个地址

 

 

报错1:

Access to XMLHttpRequest at 'http://localhost:8089/appcicd/appinfo/getappinfos' from origin 'http://localhost:8000' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value 'http://localhost:8089/' that is not equal to the supplied origin.
Index.js:79 Error: Network Error
    at createError (createError.js:16)

 

报错2:

Access to XMLHttpRequest at 'http://localhost:8089/appcicd/appinfo/getappinfos' from origin 'http://localhost:8000' 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.
 
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

 

说明:

报错1是完全没设置允许跨域,报错2是设置了允许跨域,但是跨域的域名设置了*,不允许设置*通配符导致的

 

解决方法:

1、解析请求来源的域名

2、将请求的域名设置为允许跨域

具体代码实现如下:

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
    
                response.setCharacterEncoding("UTF-8");//设置编码格式
                response.setContentType("application/json;charset=UTF-8");
 
                String originalURL = request.getHeader("Origin");
                if (originalURL != null) {
                    logger.info(" Origin=", request.getHeader("Origin"));
                    response.addHeader("Access-Control-Allow-Origin", originalURL);
                }
                response.addHeader("Access-Control-Allow-Credentials", "true");
                ServletOutputStream outputStream = response.getOutputStream();
                JSONObject result = new JSONObject();
                result.put("respCode", -11);
                result.put("errMsg", "用户没有此操作权限!");
 
                outputStream.write(JSONObject.toJSONString(result).getBytes());
 
                return false;
           
}

*如果想通用配置服务器上的接口允许跨域,参考另一篇随笔:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lst0426

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值