目前正在开发中的项目原本是springMVC + JSP开发,现阶段要全部使用vue进行前端开发。由于前端开发的域名与服务器接口原域名不一致,所以vue中所有的ajax请求都涉及到跨域问题。
直接上代码,需要前端与服务器都进行设置:
1、前端ajax设置属性xhrFields
$.ajax({
url: 'xxx',
type: 'get',
xhrFields: {
withCredentials: true
},
success: function(data){
console.log(data);
}
})
2、服务端设置响应请求头信息
一般在web.xml配置filter拦截器,在拦截器中进行设置
public class HeaderFilter implements Filter {
private static final Logger logger = LoggerFactory.getLogger(HeaderFilter.class);
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
String originHeader = request.getHeader("Origin");
response.setHeader("Access-Control-Allow-Origin", originHeader);
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "0");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type,Token,Accept, Connection, User-Agent, Cookie");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("XDomainRequestAllowed", "1");
filterChain.doFilter(request, response);
}