简体   繁体   中英

localStorage won't store data

I have a demo of a simple Login and Logout application with access token. If the user haven't login yet and they try to access other page, which mean access token is null, they will be direct back to Login page. I use sessionStorage to store user token and it work fine. When I try using localStorage, my application won't work anymore. It still login in but for an instance moment, it direct me back to the Login page like my token isn't saved at all. It still generate new token after successfully login so I guess it having something to do with localStorage.

Edit: I just checked back and they both storage my token but I can't parse it to other pages with localStorage.

My Login Page Code:

$('#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');
                }
            });
        });

Other page base code:

if (localStorage.getItem('accessToken') == null) {
            window.location.href = "Login.html";
        }

Are you sure that response.access_token does not come null?

You can check it from the development tools in Chrome (Windows: Ctrl + Shift + i or macOs: command + option + i )> Application > Storage > Local Storage:

如您所见,该值可以设置为 null

As you can see the value can be set null.

I hope it helps.

localStorage supports only string values. Chances are response.access_token might not be a string value. So try this instead:

localStorage.setItem("accessToken", JSON.stringify(response.access_token));

And While retrieving,

JSON.parse(localStorage.getItem("accessToken"))

Try to save object in localstorage use following method (as shown in https://stackoverflow.com/a/2010948 )

var testObject = { 'one': 1, 'two': 2, 'three': 3 };

// Put the object into storage
localStorage.setItem('testObject', JSON.stringify(testObject));

// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');

console.log('retrievedObject: ', JSON.parse(retrievedObject));

And in your code we can do it like this

$('#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) {
                    var obj= { 'accessToken': response.access_token};
                    localStorage.setItem(JSON.stringify(obj));
                    window.location.href = "User.html";
                },
                // Display errors if any in the Bootstrap alert <div>
                error: function (jqXHR) {
                    $('#divErrorText').text(jqXHR.responseText);
                    $('#divError').show('fade');
                }
            });
        });

I have a demo of a simple Login and Logout application with access token. If the user haven't login yet and they try to access other page, which mean access token is null, they will be direct back to Login page. I use sessionStorage to store user token and it work fine. When I try using localStorage, my application won't work anymore. It still login in but for an instance moment, it direct me back to the Login page like my token isn't saved at all. It still generate new token after successfully login so I guess it having something to do with localStorage.

Edit: I just checked back and they both storage my token but I can't parse it to other pages with localStorage.

My Login Page Code:

$('#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');
                }
            });
        });

Other page base code:

if (localStorage.getItem('accessToken') == null) {
            window.location.href = "Login.html";
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM