我有一个带有访问 token 的简单“登录和注销”应用程序的演示。如果用户尚未登录,并且他们尝试访问其他页面,这意味着访问 token 为空,那么他们将直接返回“登录”页面。我使用sessionStorage来存储用户 token ,并且工作正常。当我尝试使用localStorage时,我的应用程序将无法再使用。它仍然可以登录,但是在某些情况下,它将我带回到“登录”页面,就像我的 token 根本没有保存一样。成功登录后,它仍会生成新 token ,因此我认为它与localStorage有关。
编辑:我刚刚检查回来,他们都存储我的 token ,但我无法使用localStorage将其解析到其他页面。
我的登录页面代码:
$('#btnLogin').click(function () {
$.ajax({
url: '/token',
method: 'POST',
contentType: 'application/json',
data: {
userName: $('#txtFullname').val(),
password: $('#txtPassword').val(),
grant_type: 'password'
},
// Khi đăng nhập thành công, lưu token vào sessionStorage
success: function (response) {
//sessionStorage.setItem("accessToken", response.access_token);
localStorage.setItem("accessToken", response.access_token);
window.location.href = "User.html";
//$('#divErrorText').text(JSON.stringify(response));
//$('#divError').show('fade');
},
// Display errors if any in the Bootstrap alert <div>
error: function (jqXHR) {
$('#divErrorText').text(jqXHR.responseText);
$('#divError').show('fade');
}
});
});
其他页面基本代码:
if (localStorage.getItem('accessToken') == null) {
window.location.href = "Login.html";
}
最佳答案
您确定 response.access_token 不为空吗?
您可以从Chrome的开发工具中检查它(Windows: Ctrl + Shift + i 或macOs:命令+选项+ i )>应用程序>存储>本地存储:
如您所见,该值可以设置为null。
希望对您有所帮助。
关于javascript - localStorage不会存储数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62229118/