React JS Error unexpected end of json when passing user token via session-storage

心已入冬 提交于 2019-12-11 17:45:40

问题


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.


回答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'));



回答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]".


来源:https://stackoverflow.com/questions/50312738/react-js-error-unexpected-end-of-json-when-passing-user-token-via-session-storag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!