JAVA拦截器,JAVA返回结果跨域问题解决

遇到的问题:

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

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

报错1:

1Access 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. 2Index.js:79 Error: Network Error 3 at createError (createError.js:16)

报错2:

1Access 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. 2 3has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

说明:

报错1是完全没设置允许跨域,报错2是设置了允许跨域,但是跨域的域名设置了*,不允许设置*通配符导致的

解决方法:

1、解析请求来源的域名

2、将请求的域名设置为允许跨域

具体代码实现如下:

1@Override 2public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException { 3 4 response.setCharacterEncoding("UTF-8");//设置编码格式 5 response.setContentType("application/json;charset=UTF-8"); 6 7 String originalURL = request.getHeader("Origin"); 8 if (originalURL != null) { 9 logger.info(" Origin=", request.getHeader("Origin")); 10 response.addHeader("Access-Control-Allow-Origin", originalURL); 11 } 12 response.addHeader("Access-Control-Allow-Credentials", "true"); 13 ServletOutputStream outputStream = response.getOutputStream(); 14 JSONObject result = new JSONObject(); 15 result.put("respCode", -11); 16 result.put("errMsg", "用户没有此操作权限!"); 17 18 outputStream.write(JSONObject.toJSONString(result).getBytes()); 19 20 return false; 21 22}

*如果想通用配置服务器上的接口允许跨域,参考另一篇随笔:https://www.cnblogs.com/meitian/p/12797539.html

点赞
收藏

评论区

加载中...

相关推荐

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

java将前端的json数组字符串转换为列表

记录下在前端通过ajax提交了一个json数组的字符串,在后端如何转换为列表。前端数据转化与请求varcontracts{id:'1',name:'yanggb合同1'},{id:'2',name:'yanggb合同2'},{id:'3',name:'yang

vue 使用axios 出现跨域请求的两种解决方法

最近在使用vueaxios发送请求,结果出现跨域问题,网上查了好多,发现有好几种结局方案。1:服务器端设置跨域header(“AccessControlAllowOrigin:\”);header(“AccessControlAllowHeaders:contenttype”);header(“AccessCont

java基础知识随身记

2018年11月12日20:51:35一、基础知识:1、JVM、JRE和JDK的区别:JVM(JavaVirtualMachine):java虚拟机,用于保证java的跨平台的特性。  java语言是跨平台,jvm不是跨平台的。JRE(JavaRuntimeEnvironment):java的运行环境,包括jvmjava的核心类

springboot的跨域

https://www.cnblogs.com/520playboy/p/7306008.html1、对于前后端分离的项目来说,如果前端项目与后端项目部署在两个不同的域下,那么势必会引起跨域问题的出现。针对跨域问题,我们可能第一个想到的解决方案就是jsonp,并且以前处理跨域问题我基本也是这么处理。但是jsonp方式也同样有不足,不管是对

SpringBoot 优雅配置跨域多种方式及Spring Security跨域访问配置的坑

前言最近在做项目的时候,基于前后端分离的权限管理系统,后台使用SpringSecurity作为权限控制管理,然后在前端接口访问时候涉及到跨域,但我怎么配置跨域也没有生效,这里有一个坑,在使用SpringSecurity时候单独配置,SpringBoot跨越还不行,还需要配置Security跨域才行。什么是跨域跨域是一种浏览器同源安全策略,即浏