• 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;
               
    }
    *如果想通用配置服务器上的接口允许跨域,参考另一篇随笔:https://www.cnblogs.com/meitian/p/12797539.html 
  • 相关阅读:
    ubuntu 14.04 firefox install flash-plugin
    ubuntu node.js Binaries方式安装(二进制文件安装)
    ubuntu14.04 截图
    ubuntu 14.04下,thinkpad触摸板关闭方法
    ubuntu Mozilla Firefox install flash plugin 火狐浏览器安装flash插件
    win7+ubuntu 14.04双系统 硬盘安装
    后台启动VirtualBox虚拟机
    excel vlookup函数使用方法
    图片添加文字水印和图片水印
    记录使用Stream转多层map数据结构及遇到的坑
  • 原文地址:https://www.cnblogs.com/meitian/p/12797456.html
Copyright © 2020-2023  润新知