springboot redis 缓存跨域丢失问题
对于前后端分离的项目,在开发阶段经常会遇到跨域的问题。
1.首先,对于后台的处理方式,第一种是用 @CrossOrigin 注解,@crossorigin是后端SpringMVC框架(需4.2版本以上)Controller层的一个注解,这个注解是用在控制器方法上的,但这种方式不能做到统一跨域处理
@CrossOrigin(origins = "http://localhost:3000") @RequestMapping(method = RequestMethod.GET) List<User> getList() { return Lists.newArrayList(userdb.asMap().values()); }
2. 第二种方式是 构建一个拦截器
import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Component; public class SimpleCORSFilter implements Filter { public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; HttpServletRequest request= (HttpServletRequest)req; response.setHeader("Access-Control-Allow-Credentials","true");//允许跨域加载 response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "x-requested-with");//ajax请求 chain.doFilter(req, res); } public void init(FilterConfig filterConfig) { } public void destroy() {} }
3.当然,前端ajax请求时,也可以做相应的处理,关键代码 crossDomain: true, xhrFields: { withCredentials: true }
$.ajax({ type: "POST", url: window.ServiceUrl+"/custom/clientLogin", crossDomain: true, xhrFields: { withCredentials: true }, data: {username:loginName,password:password}, dataType : "json", success: function(respMsg){ //正常操作 }, error:function(){ //异常操作 } });
4.如果上述方法都不行,可以检查一下cookie的domain和path属性:这里引用一下大佬的章
https://blog.csdn.net/zhouziyu2011/article/details/61200943