How can I store an access token received from the backend (in JSON format) in local storage and use it to log in?

My goal is to create a login interface using Plain Javascript. I have obtained a Token from the backend and now need assistance in utilizing this Token for the login process and storing it in LocalStorage.

Although I have successfully made the API call, I am encountering a 502 (Bad Gateway) error. It seems like the issue might be related to not properly setting the token.

function postData() {
    var result = fetch('https://example.api.com/login', {
        method: "POST", 
        mode: "cors",
        cache: "no-cache",

        headers: {
            'Content-Type': 'application/json; charset=utf-8',
            'Access-Control-Allow-Origin': '*',
            'Accept': 'application/json'    
        },

        redirect: "follow",
        referrer: "no-referrer",

        body: JSON.stringify({
            isArray: false,
            data: {
                    email: document.getElementById("email").value,
                    password: document.getElementById("passwordNew").value
                }
        })

    }).then(response => response.json()); 
    console.log("result :" + result);
    return result;
}

This code snippet shows the API call being made, which returns the token as part of the response.

The received response includes the following details:

"data": {
    "token": "sdfsdgsfgsgsgssb497e7764f4df8cb504a122cc18b2eed8",
    "startTime": 1558417495078,
    "endTime": 1558503895078
}

Upon successful utilization of the token provided by the backend, I expect to achieve a successful login by entering my email and password.

Answer №1

Upon receiving the token from your login request, it is crucial to securely store it for future use. Storing the token in localStorage seems like a step in the right direction. I would also recommend implementing the async/await syntax for better readability and usability. By leveraging promises, this syntax simplifies the code structure by replacing resolve/reject functions with try/catch blocks.

async function handleLogin(username, password) {
  try {
    let response = await fetch('https://example.api.com/login', {
        method: "POST",
        mode: "cors",
        cache: "no-cache",
        headers: {
            'Content-Type': 'application/json; charset=utf-8',
            'Access-Control-Allow-Origin': '*',
            'Accept': 'application/json'    
        },
        redirect: "follow",
        referrer: "no-referrer",
        body: JSON.stringify({
            isArray: false,
            data: {
                    email: document.getElementById("email").value,
                    password: document.getElementById("passwordNew").value
                }
        })
    })
    response = response.json();
    window.localStorage.setItem('token', response.data.token)
  } catch(error) {
    console.log('error while logging in', error)
  }
}

When using the stored token for subsequent requests, retrieve it from localStorage as shown below:

async function editProfile(updatedProfileInfo) {
  const token = localStorage.getItem('token');
  try{
    let response = await fetch('https://someurl.com/edit', {
      method: "POST",
      ...
      'x-access-token': token,
      ...
    })
  //handle response
  } catch(error) {}
}

Here are some key points to keep in mind:

  1. Ensure that you understand how your API requires tokens to be included in requests. In the example provided, the token is placed in the x-access-token section of the request header. Different APIs may have different requirements such as using cookies. Always verify the correct method for passing the token.
  2. Prior to sending a request, it is advisable to validate the token's expiration status. It might be beneficial to store the entire login response, including expiration details, so you can check its validity before making the call. If the token is invalid, log the user out and remove the token from localStorage accordingly.

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

Implementing advanced checkbox filtering feature in React

Does anyone have experience with creating dynamic Checkbox filtering in React using Material-UI? I'm finding it challenging because the checkbox options are generated dynamically from incoming data and need to be categorized by type of Select componen ...

Non-responsive Click Event on Dynamically Created Div Class

I am facing some uncertainty in approaching this problem. In the HTML, I have created buttons with additional data attributes. These buttons are assigned a class name of roleBtn. When clicked, they trigger the jQuery function called roleBtnClicked, which ...

Can you please explain the distinction between angular.equals and _.isEqual?

Do these two options offer different levels of performance? Which one excels at conducting deep comparisons? I've encountered situations where Angular's equals function fails to detect certain differences. In addition, I've observed that th ...

Finding the latitude and longitude coordinates of a point at a specific distance from another using Node.js or JavaScript

My task involves determining the square area based on a latitude and longitude (x,y) as shown in the provided figure. To accomplish this, I must calculate the coordinates of the remaining three corners by adding 10 kilometers to each side. I will be using ...

Is it possible for a mobile web application to continue running even when the screen is

Thinking about creating a mobile web application with the use of jQuery Mobile for tracking truck deliveries. I'm interested in sending GPS coordinates back to the server periodically. Is this possible even when the screen is turned off? If not, any ...

Error encountered with AngularJS code when attempting to load content from another page using ajax

I'm currently tackling a challenge with AngularJs and php. Whenever I try to load content from another page, AngularJs seems to stop working. Let me provide you with a sample code snippet to illustrate my issue. main-page.php <div id="form-secti ...

Utilize or Bring in an external JavaScript file within Ionic 2

Currently working with Ionic 2 and Typescript Angular 2 and facing an issue. I need to utilize an external JavaScript file located at . How can I import or include this in my project? ...

Step-by-step guide on concealing elements and subsequently displaying them upon clicking the containing DIV

It's a bit tricky to explain without visuals, so I suggest checking out the JSFiddle link provided. Essentially, when a specific div is clicked, it should expand to reveal some inputs and buttons. However, the issue I'm facing is that upon loadin ...

Verify and generate a notification if the value is null

Before saving, it is important to check for any null values and alert them. I have attempted to do so with the following code, but instead of alerting the null values, the data is being saved. . function fn_publish() { var SessionNames = getParamet ...

Tips for resolving import errors encountered after running npm start

I recently started using React and I am currently following a tutorial. Even though I have the exact same code as the tutorial, I'm encountering the following error. ./src/index.js Attempted import error: './components/App' does not have a ...

What is the timing for when the SignalR connection is terminated from the browser?

Currently, I am developing a chat application using SignalR 2.0, like many others in the same field. In my Win8.1 application, when the user closes the application, the hub receives the OnDisconnected event and removes the user from the list on the hub. A ...

Having trouble with res.render() when making an axios request?

I am encountering an issue with my axios requests. I have two requests set up: one to retrieve data from the API and another to send this data to a view route. const response = await axios({ method: 'POST', url: 'http:// ...

Scheduling tasks for jQuery/Javascript like a Cronjob

I'm currently working on a web application that predominantly uses PHP, however, I am incorporating jQuery/Javascript to retrieve Tweets from users' URLs at http://twitter.com/status/user_timeline/joebloggs.json?count=1&callback=. My aim is ...

What are the steps to leverage an Azure function for extracting JSON data from a URL that points to either a JSON file or a text file containing JSON data

public static async Task<string> MakeSlackRequest(string message) { var urlJsonData = "{'text':'message'}"; // Transforming url with JSON data into a JSON string using(var client = new HttpClient()) { ...

Is Selenium suitable for testing single page JavaScript applications?

As a newcomer to UI testing, I'm wondering if Selenium is capable of handling UI testing for single-page JavaScript applications. These apps involve async AJAX/Web Socket requests and have already been tested on the service end points, but now I need ...

Python: Transforming Json Timestamp to Datetime

Is there a way to convert the datetime string '2021-11-21T18:57:18.000+01:00' from JSON to a datetime object in Python? timestamp = datetime.datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%S.%fZ") When I try this code snippet, it throws ...

Can you explain how to break down secured routes, users, and posts all within a single .create() function in Mongoose/JavaScript

I am seeking guidance on utilizing the .create() method within a protected route while implementing deconstructed JavaScript. In the absence of the protected route, I can deconstruct my schema and utilize req.body in .create(...) as shown below. const { ti ...

best practice for parsing JSON strings in Java

I have a JSON string/response that I need to parse in a simple way to extract objects/arrays. The structure may be complex and repeated, so I need to retrieve the data list by list. Most parsers only work with basic JSON structures, but mine is a bit mor ...

NextJS: encountered an error with fallback enabled

I have my NextJS setup on Vercel and here is how I configured getStaticPaths: const paths = posts.map((post) => ({ params: { player: post.player, id: post.id }, })) return { paths, fallback: true } However, when I set the fallback to true, I ...

Tips on using CSS to hide elements on a webpage with display:none

<div class="span9"> <span class="disabled">&lt;&lt; previous</span><span class="current numbers">1</span> <span class="numbers"><a href="/index/page:2">2</a></span> <span class="num ...