最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React JS how to pass values between pages using session storage - Stack Overflow

programmeradmin1浏览0评论

I have a react JS login page that accepts the user name and password. Upon entering the user name and and password, the credentials are processed against a json (API) file, which generates a token for the client. My goal is to pass the token to a landing page after the client has logged in and populate a dropdown list with the clients respective data. The problem I am facing is getting the clients token to pass from my login page to the landing page.

In my login page, I am using Fetch to retrieve the token from the API and then store the token using session-storage. The code snippet for getting the token:

ponentDidMount() {  
        this.fetchData(); 
    } 

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

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

Landing page

ponentDidMount() {
        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 }))
    }

...going back to the login page, I confirmed that I'm getting the token via fetchData function, but the problem I am encountering is properly storing the token so that it may be passed to the landing page.

FYI- I've already built the landing page and it functions properly when I manually copy the generated token into the Authorization section of the Fetch. ...Could, I please get some help as to what I'm doing wrong?

I have a react JS login page that accepts the user name and password. Upon entering the user name and and password, the credentials are processed against a json (API) file, which generates a token for the client. My goal is to pass the token to a landing page after the client has logged in and populate a dropdown list with the clients respective data. The problem I am facing is getting the clients token to pass from my login page to the landing page.

In my login page, I am using Fetch to retrieve the token from the API and then store the token using session-storage. The code snippet for getting the token:

ponentDidMount() {  
        this.fetchData(); 
    } 

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

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

Landing page

ponentDidMount() {
        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 }))
    }

...going back to the login page, I confirmed that I'm getting the token via fetchData function, but the problem I am encountering is properly storing the token so that it may be passed to the landing page.

FYI- I've already built the landing page and it functions properly when I manually copy the generated token into the Authorization section of the Fetch. ...Could, I please get some help as to what I'm doing wrong?

Share Improve this question edited May 13, 2018 at 17:13 Code-Apprentice 83.7k26 gold badges161 silver badges285 bronze badges asked May 12, 2018 at 18:09 user1724708user1724708 1,4697 gold badges31 silver badges57 bronze badges 3
  • Does the token get stored to session storage? – Agney Commented May 12, 2018 at 18:21
  • Is login and landing on different domains? if not, why not use sessionStorage.getItem like you did before? – Femi Oni Commented May 12, 2018 at 18:22
  • @Boy With Silver Wings - no and that is what am struggling with (getting the token stored within the session storage) ...I reviewed my syntax, but cannot seem to discover why the token is not getting stored. In the Login page snippet, I attempted a console.log to see if the token is being capture, but I got a message indicating the it was unreachable (on the line where I wrote on console.log). Am I implementing the console.log (please see function requestUserInfo) in the right section? Please let me know if you have any suggestions, I'm still kind of new to React. both page (same domain ) – user1724708 Commented May 12, 2018 at 18:54
Add a ment  | 

1 Answer 1

Reset to default 4

The problem is here:

.then(data => this.setState({ data: data }))
.then(data => sessionStorage.setItem('token', data))

setState doesn't resolve a Promise so it does not have then()

Change it to something like:

.then(data => {
  this.setState({ data: data })
  sessionStorage.setItem('token', data)
})

In landing page:

ponentDidMount() {
        fetch('http://myapiclients/api/clients', {
            method: 'GET',
            headers: {
                'Content-type': 'application/json',
                'Authorization': 'Bearer ${token}'  // token is not defined!
            },
        })
        .then(results => results.json())
        .then(data => this.setState({ data: data }))
    }

token is not defined, so it will be 'Bearer undefined', either define it before fetch(...) with sessionStorage.getItem("token") or in fetch headers do something like:

'Authorization': 'Bearer ' + sessionStorage.token
发布评论

评论列表(0)

  1. 暂无评论