简体   繁体   中英

I keep getting the error unexpected token b in JSON at position 0 at JSON.parse?

So I got this code that creates a html page.The function signup allows the user to register and create a password. The function checkpassword is to check if the correct password is entered for the username.It seems I have a problem in getting the item from local storage in my checkPassword function?Help will be much appreciated as I've been stuck for hours?

const PREFIX = "monash.eng1003.passwordApp.";

function checkPassword() {
  var user = document.getElementById("registerUsername").value;
  var username = document.getElementById("username").value;
  var password = document.getElementById("password").value;
  var passwordToCheck = localStorage.getItem(PREFIX + user);
  var passwordTwo = JSON.parse(passwordToCheck);

  if (password != passwordTwo) {
    alert("Don't hack" + user);
  } else {
    alert("Welcome" + user);
  }
}

function signup() {
  var user = document.getElementById("registerUsername").value;
  var pass1 = document.getElementById("registerPassword").value;
  var pass2 = document.getElementById("confirmPassword").value;
  if ((pass1 === pass2) && (pass1 !== "")) {
    if (localStorage) {
      var passwordToStore = pass1;

      localStorage.setItem(PREFIX + user, passwordToStore);
      alert("Account created for username: " + user);
    }
  } else {
    alert("Passwords must match and cannot be empty.")
  }
}

EDIT:Thanks for pointing out that I do not need to parse it since I didn't stringify.That solved the problem but since I cannot delete the post I have to leave it here

You didn't convert the password to JSON when you stored it, so you don't need to use JSON.parse() when you retrieve it. You stored an ordinary string, you can just retrieve it and use it.

passwordTwo = localStorage.getItem(PREFIX + user);

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