解決前後端分離後的Cookie跨域問題
阿新 • • 發佈:2018-02-11
-o equals eth success ati $.ajax 設置 ons post
一. 前端Ajax關鍵配置
$.ajax({ type: "post", url: xxx, data: xxx, contentType: ‘application/json‘, dataType: "json", xhrFields: { withCredentials: true }, success: function (data) { } })
二、後端過濾器關鍵配置
//解決Cookie跨域問題 response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); response.setHeader("Access-Control-Allow-Credentials", "true"); response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); response.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE"); //解決 Content-Type:application/json 時跨域設置失敗問題 if("OPTIONS".equals(request.getMethod())) { //放行OPTIONS請求 filterChain.doFilter(request, response); return; }
註意:
- "Access-Control-Allow-Origin" 不能設置成 "*"
- 當 Content-Type 為 application/json 時,Ajax實際會發兩次請求,第一次是一個OPTIONS請求,這時過濾器一定得放開
解決前後端分離後的Cookie跨域問題