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 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM