关于请求跨域及response中Set-Cookie无效问题记录

最近开发一个项目,项目前后端完全分离,即

页面放在192.168.0.105:8080中,

服务端放在192.168.0.105:57500中,

这样前台发送请求后会出现跨域问题,针对跨域问题,解决思路为处理响应头,步骤如下

1.定义一个过滤器,在web.xml中配置

 


    ajaxFilter
    com.tbms.filter.AjaxFilter
  
  
    ajaxFilter
    /*
  

2.在过滤其中处理响应头

 
  1. public class AjaxFilter extends OncePerRequestFilter{

  2.  
  3. @Override

  4. protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)

  5. throws ServletException, IOException {

  6. System.out.println("拦截到了" + request.getRequestURL());

  7. response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));

  8. response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, If-Modified-Since");

  9. response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");

  10. response.setHeader("Access-Control-Max-Age", "3600");

  11. response.addHeader("Access-Control-Allow-Credentials", "true");

  12. response.setCharacterEncoding("UTF-8");

  13. response.setContentType("application/json");

  14. //此行代码确保请求可以继续执行至Controller

  15. filterChain.doFilter(request, response);

  16. }

  17. }

3.前台发送请求

 
  1. $.ajax({

  2. type: "post",

  3. url: that.ip + that.port + that.prjName + "/login",

  4. data: JSON.stringify(loginInfo),

  5. contentType: "application/json",

  6. dataType: "json",

  7. xhrFields: {withCredentials: true},

  8. success: function(rs) {

  9. if(rs.state == 'success'){

  10. that.SelectCompany = false;

  11. that.$router.push("/index/res/signet")

  12. }

  13. },

  14. error: function(){

  15. alert("用户名密码错误!");

  16. },

  17. });

PS:1.第二步中红色代码"Access-Control-Allow-Origin"对应的值不能为通配符“*”。
2.response.addHeader("Access-Control-Allow-Credentials", "true"); 该行代码表示允许跨域发送Cookie

3.在ajax请求中应加入xhrFields: {withCredentials: true},否则,依然不会发送Cookie

你可能感兴趣的:(跨域访问)