最近开发一个项目,项目前后端完全分离,即
页面放在192.168.0.105:8080中,
服务端放在192.168.0.105:57500中,
这样前台发送请求后会出现跨域问题,针对跨域问题,解决思路为处理响应头,步骤如下
1.定义一个过滤器,在web.xml中配置
<filter>
<filter-name>ajaxFilter</filter-name>
<filter-class>com.tbms.filter.AjaxFilter</filter-class><!-- 自定义过滤器 -->
</filter>
<filter-mapping>
<filter-name>ajaxFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
2.在过滤其中处理响应头
public class AjaxFilter extends OncePerRequestFilter{
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
System.out.println("拦截到了" + request.getRequestURL());
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, If-Modified-Since");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.addHeader("Access-Control-Allow-Credentials", "true");
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json");
//此行代码确保请求可以继续执行至Controller
filterChain.doFilter(request, response);
}
}
3.前台发送请求
$.ajax({
type: "post",
url: that.ip + that.port + that.prjName + "/login",
data: JSON.stringify(loginInfo),
contentType: "application/json",
dataType: "json",
xhrFields: {withCredentials: true},
success: function(rs) {
if(rs.state == 'success'){
that.SelectCompany = false;
that.$router.push("/index/res/signet")
}
},
error: function(){
alert("用户名密码错误!");
},
});
PS:1.第二步中红色代码
"Access-Control-Allow-Origin"对应的值不能为通配符“*”。
2. response.addHeader("Access-Control-Allow-Credentials", "true"); 该行代码表示允许跨域发送Cookie
3.在ajax请求中应加入xhrFields: {withCredentials: true},否则,依然不会发送Cookie