• 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 
  • 相关阅读:
    模板
    模板
    模板
    模板
    2017-2018 ACM-ICPC Asia Tsukuba Regional Contest
    牛客
    软件工程
    Codeforces Round 696(Div.2)
    Atcoder ARC111 contest
    Codeforces Educational Round 100(Div.2)
  • 原文地址:https://www.cnblogs.com/meitian/p/12797456.html
Copyright © 2020-2023  润新知