前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >JAVA拦截器,JAVA返回结果跨域问题解决-has been blocked by CORS policy

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

作者头像
用户3519280
发布2023-07-07 18:38:35
2370
发布2023-07-07 18:38:35
举报
文章被收录于专栏:c++ 学习分享c++ 学习分享

遇到的问题:

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

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

报错1:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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、将请求的域名设置为允许跨域

具体代码实现如下:

代码语言:javascript
复制
@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;
           
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021-06-05,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 遇到的问题:
  • 解决方法:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档