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

2023-07-07 18:38:35 浏览数 (3)

遇到的问题:

通过拦截器做权限控制,没有权限时返回了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;
           
}

1 人点赞