1.後端允許跨域調用,並添加Cookie
@CrossOrigin
@RequestMapping(value="/login", produces = "application/json; charset=utf-8", method=RequestMethod.POST)
@ApiOperation(value = "用戶登錄")
@ApiImplicitParams({
@ApiImplicitParam(name = "name", value = "用戶名", required = true, dataType = "string"),
@ApiImplicitParam(name = "pwd", value = "密碼", required = true, dataType = "string")
})
@ApiResponses({
@ApiResponse(code = 200, message = "result", response = result.class)
})
public Object login(HttpServletRequest request,
HttpServletResponse response,
@RequestParam(value="name")String name,
@RequestParam(value="pwd")String pwd) {
System.out.println("login:");
//1.驗證
result ret = new result(200, "登錄成功", 0, tutil.currMSecs(), null);
//略
//
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
String sSessionId = UUID.randomUUID().toString().replaceAll("-", "");;
Cookie ck = new Cookie(sdpt.SEN_ID, sSessionId);
ck.setPath("/");
ck.setMaxAge(30*1000*60);
response.addCookie(ck);
HttpSession session = request.getSession();
session.setAttribute(sdpt.SEN_ID, sSessionId);
return ret;
}
2.前端允許跨域
form.on('submit(hug_adminLogin)', function(data) {
console.log(data.field)
// 登錄
$.ajax({
type: "post",
url: 'http://xx.xxx.xx.xxx:8080/xxxx/syssetup/login',
data: {
name : 'xxxx',
pwd : 'x'
},
dataType: "json",
xhrFields: {
withCredentials:true
},
crossDomain: true,
success: function(res){
console.log(res);
if(res.code == 200){
layer.msg(res.msg);
}else{
layer.msg(res.msg);
}
}
});
})
結果:
結果2
但是在Application裏面都沒有Cookie,所以下次請求了,也沒帶上
問題就是怎麼才能帶上Cookie