项目前后端分离各自做独立站点开发,使用jQuery.ajax方法 开发登录功能,登录后跳转内页,内页同样使用ajax读取会员数据。
ajax执行前注意设置
$.ajaxSetup({
xhrFields: {withCredentials: true}
});
如果没有 withCredentials: true ,
后端session就会读不出信息。
同时,后端跨域代码:
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class Kuayu implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
String url = request.getHeader("Origin");
response.setHeader("Access-Control-Allow-Origin", url);
response.addHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT,OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, X-Requested-With");
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {
}
public void destroy() {
}
}
平常跨域 Access-Control-Allow-Origin:* ,在此处针对Session的读取需要修改成前端站点所用的域名,并且加上 Access-Control-Allow-Credentials:true。