1. 程式人生 > >JWT中token在前端的所有操作

JWT中token在前端的所有操作

  • 獲取token
$.ajax({
		url: "http://localhost:8080",
		data: { data: "data" },
		type: "POST",
		dataType: "json",
		async: false,
		cache: false,
		success: function(data,headers) {
			console.log(data);
			console.log(headers);//一般是在這裡拿,要看後端是煮麵封裝的
		},
		error: function(data) {
			console.log(data);
		}
	});
  • 將token存入瀏覽器cookie
	function setTokenToCookie(value) {
		var Days = 1; //此 cookie 將被儲存 30 天
		var exp = new Date();
		exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
		document.cookie = "my_token =" + escape(value) + ";expires=" + exp.toGMTString();
	}
  • 將token從瀏覽器cookie中取出
function getCookie(name) {
		var cookieValue = "啥也沒有!!";
		if (document.cookie && document.cookie !== '') {
			var cookies = document.cookie.split(';');
			for (var i = 0; i < cookies.length; i++) {
				var cookie = $.trim(cookies[i]);
				if (cookie.substring(0, name.length + 1) === (name + '=')) {
					cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
					break;
				}
			}
		}
		return cookieValue;
	}
  • 傳送ajax請求時新增token到請求頭
	$.ajax({
		url: "http://localhost:8080",
		data:{data:"data"},
		type: "POST",
		dataType: "json",
		headers: {
			Token: my_token //這裡是Token
		},
		async: false,
		cache: false,
		success: function(data) {
			console.log(data);
		},
		error: function(data) {
			console.log(data);
		}
	});