0

I have a login page, which excepts the username and password. Upon button submission, the page processes the user credentials via a JSON / API and generates a token thus routing the user over to a landing that presents the client with a drop-down of their respective info.

My login page is getting the user token from the API (confirmed via console.log), but the problem I'm encountering is getting the token to pass from the login page over to the landing page.

Now, when I manually paste the generated token into my landing page, the dropdown list displays the user's data, so the issue is getting the generated token to pass over to the landing page.

First, in the login page, I have a function for retrieving the client's token from the API. I call this function on button submit:

componentDidMount() {  
    this.fetchData(); 
} 

//request the token
fetchData() {
    return fetch('http://myapiauth:11111/api/auth', {
        method: 'POST',
        headers: {
            'Content-type': 'application/json',
        },
         body: JSON.stringify({
            username: 'myadminName',
            password: 'myPassword',
            Authorization: 'myPassword',
        })
    }) /*end fetch */
    .then(results => results.json())
    .then(data => {
        this.setState({ data: data })
        sessionStorage.setItem('token', JSON.stringify(data))
      })
    }

  //authenticate request
  requestUserInfo() {
    var token = JSON.parse(sessionStorage.getItem('token'));
    return fetch('http://myapiauth:11111/api/auth', {
      method: 'GET',
      headers: new Headers({
        Authorization: 'Bearer ' +sessionStorage.token
      }),
    })
      .then((response) => response.json());
  }

Login Full Code: https://codepen.io/lkennedy009/pen/mLKPLv?editors=0010#0

...for the landing page, in the snippet below, am retrieving the token from the login page:

componentDidMount() {
    fetch('http://myapiclients:22222/api/clients', {
        method: 'GET',
        headers: {
            'Content-type': 'application/json',
            'Authorization': 'Bearer ' +sessionStorage.token
        },
    })
    .then(results => results.json())
    .then(data => this.setState({ data: data }))
}

Landing Page full code: https://codepen.io/lkennedy009/pen/ELRKpw?editors=0010#0

Could I please get some help as to what am doing wrong? I've checked my syntax / setup and compared against other online resources, but still unable to figure out the issue.

2 Answers 2

2

You need to stringify the data into sessionStorage. Otherwise it's going to look like this "[object Object]". This is because localStorage and sessionStorage can only store DOMStrings and not objects. The documentation for Storage.setItem

Simple test to verify:

sessionStorage.setItem('token', {'a':1})
let t = sessionStorage.getItem('token')
// "[object Object]".
Sign up to request clarification or add additional context in comments.

Comments

1

As Henrik has posted, you will have to set the value to local Storage as,

sessionStorage.setItem('token', JSON.stringify(data))

and use it as,

var token = JSON.parse(sessionStorage.getItem('token'));

8 Comments

Thank you, that resolved the issue as to why the token was not being stored in the session. However, my landing page still errors out: (unexpected end of json) ...on my landing page, in the Fetch, am I using the proper syntax? I updated my coding snippet & code pen. Could you take a look please ?
Again 'Authorization': 'Bearer ' +localStorage.getItem('token') is the correct format
ok, I've re-confirmed, however, my landing page is still rendering the same error. on the landing page, when I manually copy/paste the token into the fetch, the page refreshes without errors and I see the clients data. I ensured that my headers reflect the following: 'Authorization': 'Bearer ' +sessionStorage.getItem('token') ...in my function: requestUserInfo(), which is called in the Login page and in the fetch of my landing page. Could there possibly be an issue in the way I have my credentials set in the header of the fetch being used in my fetchData() function where am using post?
...I notice in my console, that I get a 401 (Unauthorized) error in reference to the client API, so am wondering if within my Post, is my header properly formatted?
Its not, 'Authorization': 'Bearer ' +sessionStorage.getItem('token'), its, localStorage. And you can verify whether you are really storing the value in your localStorage by going to the applications tab in your developer console in browser
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.