ajax 返回response 获取 headers中的token

登录前token的存取

//后端存入token
//浏览器默认是不让获得header中其他值,先指定一个头部,再存入数据

//HttpServletResponse response
response.setHeader("Access-Control-Expose-Headers", "TOKEN_NAME");
response.setHeader("TOKEN_NAME", "*****");

//前端ajax取token


```javascript
function a() {
	$.ajax({
		type: "POST",
		url: "/loginsuccess",
		data: formDatas,
		//注意,这里三个参数data, textStatus, request缺一不可
		success: function(data, textStatus, request) {
		  let tokenid2 = request.getResponseHeader("TOKEN_NAME")
		  console.log("tokenid="+tokenid); 
		  window.localStorage.tokenId = tokenId;
		  //这里将获取到的token存储起来,下次用的时候就使用这个tokenid
		},
	});
}

## 登录后token的存取

前端ajax发送token
   

```javascript
function a() {
	$.ajax({
		type: "post",
		url: "http://xxxx/currentuser",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		headers: {		//这里将存储的token取出发送至后端
		tokenId: localStorage.getItem("tokenId")
		},
		success: function (data, textStatus, request) {
		
		}
	});
}

后端取出token

//HttpServletRequest request
String token = request.getHeader("tokenId");

//这里需要取出redis中token与前端获取到token进行比较,以及null判断等

你可能感兴趣的:(ajax 返回response 获取 headers中的token)