前后端分离框架前端react,后端springboot跨域问题分析
2019-04-02 12:52
2336 查看
前后端分离框架前端react,后端springboot跨域问题分析
为啥跨域了
由于前后端不在一个端口上,也是属于跨域问题的一种,所以必须解决这个问题.
前端react的设置
react设置我这里使用了fetch方式请求后端接口,所以在fentch方法里设置两个参数:
- mode: “cors”;这是前端允许跨域的设置
- credentials: ‘include’;由于我需要把浏览器的cookie传入后端,所以需要这个设置
springboot后端设置
直接上配置说吧
// An highlighted block @Configuration public class CorsConfig implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; HttpServletRequest request = (HttpServletRequest) req; String path = request.getServletPath(); //前端react项目的域名 response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT"); response.setHeader("Access-Control-Max-Age", "3600"); //设置允许访问cookie response.setHeader("Access-Control-Allow-Credentials", "true"); response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); if (request.getMethod().equals("OPTIONS")) { response.setStatus(HttpServletResponse.SC_OK); }else{ chain.doFilter(request, res); } }@Override public void destroy() { } }
由于一开始没有设置关于请求OPTIONS的设置,导致我的put,delete请求都会发送2次请求到后端,并且报错,说跨域问题,但是我这里已经做了跨域配置,所以应该不是这个问题。
if (request.getMethod().equals("OPTIONS")) { response.setStatus(HttpServletResponse.SC_OK); }else{ chain.doFilter(request, res); } }
后来翻阅了一些资料后,发现http请求,关于请求方法:get,post是基本请求,但是对于put,delete等其他请求时,浏览器会先发送一个"PreFlight"请求,这个是一个预请求。所以,当发现是这种预请求的时候,后台需要返回200的状态。这样配置完后,就ok了。
相关文章推荐
- 前后端分离,spring boot跨域问题
- spring boot 框架下前端传递时间映射到后端的Date类型问题
- vue+springboot前后端分离实现单点登录跨域问题解决方法
- vue+springboot前后端分离实现单点登录跨域问题解决方法
- springboot 解决前后端分离时的跨域问题
- spring-boot前后端分离跨域问题的解决,主要是使用cors
- react +axios 后端使用springboot进行跨域请求时数据丢失问题
- SpringBoot 解决前后端分离 跨域问题
- SpringBoot+Vue前后端分离,使用SpringSecurity完美处理权限问题(二)
- SpringBoot+Vue前后端分离,使用SpringSecurity完美处理权限问题(二)
- Spring+React前后端分离项目中跨域问题的完美解决方案
- SpringBoot+Vue前后端分离,使用SpringSecurity完美处理权限问题(六)
- SpringBoot 实现前后端分离的跨域访问(CORS)
- 前后端分离项目跨域问题分析及解决思路
- j2ee的web工程,研发过程中,无论什么架构和框架(单工程的、前后端分离的、Struts、spring等),都离不开一个问题,前后端如何传参。那么,传参究竟是什么意思呢?
- java B2B2C 源码 多级分销Springboot多租户电子商城系统-前端跨域问题的解决方案
- Spring Boot 处理前端跨域问题
- springBoot之过滤器解决前端跨域问题
- SpringBoot+Vue前后端分离,使用SpringSecurity完美处理权限问题的解决方法
- springboot+jsonp解决前端跨域问题小结