I continue to encounter the error "Unexpected token b in JSON at position 0" when attempting to parse JSON data

Having some trouble with my code that generates an HTML page. The signup function allows users to register and create a password, while the checkpassword function is supposed to verify if the correct password is entered for the given username. I seem to be encountering an issue with retrieving data from local storage in my checkPassword function. Any assistance would be greatly appreciated as I've been stuck on this 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);
 
  if (password !== passwordToCheck) {
    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: Appreciate the clarification regarding unnecessary parsing since there was no stringification needed. This resolved the issue but unfortunately, I am unable to delete the post, so it will remain here.

Answer №1

There is no need to convert the password to JSON when storing it, so using JSON.parse() when retrieving it is unnecessary. Since you stored a regular string, simply retrieve it and use it as is.

retrievedPassword = localStorage.getItem(PREFIX + username);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error occurred in next.js environment file when referencing process.env keys as strings in .env.local file

I have a .env.local file with various values stored in it. NEXT_PUBLIC_GA_ID = myvariablevalue I created a function to validate the presence of these values: export const getEnvValue = (name: string, required = true) => { const value = process.env[na ...

The logical OR operator in JavaScript (denoted as ||)

Can anyone explain the functionality of this operator in JavaScript? I have come across this operator in two different contexts: //context 1 function(e){ e = e || window.event; //context 2 if(a || b) In C or C++, I understand that the return value of th ...

Guide on converting a JSON-like string into a POJO by parsing it

My task is to map JSON data to a POJO using Jackson. I have the JSON string and corresponding POJOs provided below. Can someone guide me on how to perform this mapping successfully? JSON string : { "Application": { "id": "0", "name": "MyApp", ...

Tips on validating multiple forms with the same name in AngularJS

Hello, I am seeking a way to check the validity state of all forms outside of the form tags. For example, if any form is invalid, I want an error message to be displayed. The use of myform.$invalid doesn't seem to work for all forms or update properly ...

In backbone.js, I often encounter the issue where my attributes are saved as nil when I create a

Whenever I try to add a new affiliate, the information is saved in the database but without a name. I have been struggling to fix this issue for quite some time now. class Shop.Views.AffiliatesNew extends Backbone.View template: JST['affiliates/ne ...

"Utilizing Retrofit in an Android App to Retrieve JSON Data from a Node.js Server

Problem solved! I realized I was sending plain-text on the server. Made a change to the line: response.writeHead(200, {'Content-Type': 'application/json'}); I have a quick question. A friend suggested I look into Retrofit instead of u ...

"Enhance Your Website with Stylish Bootstrap Pop

Hello, I am trying to display a "Loading..." text or spinner image while waiting for the dynamic ajax content to load. Due to the large amount of data that needs to be fetched, it takes approximately 2-3 seconds for the content to fully load. Below is my ...

Is there a way to use SCTP with Socket.io and Node.js?

I have a new project in the works, creating a web application that will utilize web sockets to provide real-time updates for users. The plan is to seamlessly transmit changes from the back-end engine. My challenge lies in Node.js not supporting SCTP sock ...

Displaying a division when a button is pressed

Despite my best efforts, I can't seem to get the chosen div to show and hide when the button is pressed. <button id="showButton" type="button">Show More</button> <div id="container"> <div id="fourthArticle"> <i ...

Why does the implementation of my interface differ from what is specified in the TypeScript documentation?

Currently delving into the world of TypeScript documentation https://www.typescriptlang.org/docs/handbook/2/classes.html Specifically focusing on the section implements Clauses, an interesting revelation surfaces: A Word of Caution It’s worth noting t ...

Creating smooth and natural movement of a div element using Javascript (rotating and moving)

After struggling to use jquery plugins for smooth motion with the div elements I'm working on, I've decided it's time to seek some assistance. I have a group of div elements that all share a class and I want them to move around the screen c ...

Updating Key-Value pairs in an ArrayList using Angular 4

After importing json data into an arrayList and storing it in local-storage, the structure looks like this: [ { "id": 1, "name": "Albany", "manufacture": "Albany Superior Low Gi Sliced Brown Seed Bread 700g", "price": 1 ...

Accessing information from Firebase and displaying it within an Angular Controller

As a newcomer to the latest Firebase SDK (with some experience using angularfire), I set out to retrieve data and display it using Angular. This is my progress so far: var app = angular.module('dApp',[]); app.controller('listingControler&a ...

I am unable to pass a variable through a callback, and I cannot assign a promise to a

Currently, I am facing a challenge with my code where I need to loop through a hard-coded data set to determine the distance from a user-entered location using Google's web API. The issue lies in passing an ID variable down through the code so that I ...

Discovering the value of a checkbox using jQuery and Ajax

I have a challenge with sending the state of multiple checkboxes on my page back to the database using ajax. While I am comfortable working with jquery and ajax for SELECT and OPTIONS elements, I am struggling to do the same for checkboxes and extracting t ...

Problem with AngularJS Multiselect checkbox dropdown configuration

In my application, I have a pop-up that includes a multi-select dropdown menu. Here is the code for the Multi-Select Dropdown: <select name="edit_tags" class="form-control" id="advisor_article_tagsx" multiple="" required ng-model="article_selected ...

Utilizing client-side properties in an onClick event within Next.js framework

class homeNotLoggedIn extends React.Component { componentDidMount() { function logout(){ localStorage.clear() location.reload() } } render() { return ( <div> < ...

Ways to prevent recurring variables in Twitter bootstrap dialogues

I need assistance with deleting multiple links using ajax: <a id="id-1">link1</a> <a id="id-2">link2</a> <a id="id-3">link2</a> <a id="id-4">link2</a> ... This is the simplified version of my code: $(docum ...

The Ink CLI is anticipating the component to be a function

Currently delving into the world of the Ink library for constructing a console application in Javascript. Despite having experience with React, this is a different ball game. Some of the nuances are proving to be quite perplexing. I've managed to get ...

display and conceal elements according to the slider's current value

Currently, I am working on creating a slider that can show and hide elements as the slider bar moves (ui.value). Firstly, I used jQuery to create 30 checkboxes dynamically: var start = 1; $(new Array(30)).each(function () { $('#showChck') ...