前后端分离的项目,使用Ajax请求可能出现跨域的问题。
Access to XMLHttpRequest at 'http://xxx:8089/hzes/en/spectaculars/getAllEnergyDayConsume?stationId=8605320001' from origin 'http://127.0.0.1:8081' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
跨域的时候所创建的session是不会被浏览器保存下来的。所以每次进行跨域请求时,服务器都认为不是同一个浏览器所发起的请求,session也会不一样。以下将介绍如何解决跨域及session共享
1、后台构建一个拦截器,对需要跨域访问的request头部重写,解决跨域
a)、增加拦截器,代码如下
package com.hnac.hzinfo.common.utils;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* CorsFileter 功能描述:CORS过滤器
*/
@Component
public class CorsFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) servletResponse;
response.setHeader("Access-Control-Allow-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,Authorization");
response.setHeader("Access-Control-Allow-Credentials", "true");
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
b)、web.xml中增加如下配置
<filter>
<filter-name>cors</filter-name>
<filter-class>com.hnac.hzinfo.common.utils.CorsFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>cors</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
2、前端Ajax请求,解决session共享
$.ajax({
url:url,
<! -- 加上此部分 Start-- >
xhrFields: {
withCredentials: true
},
crossDomain: true,
<! -- 加上此部分 End-- >
success:function() {
},
error:function() {
}
});