簡體   English   中英

從 api 獲取 json 響應 - react.js

[英]Fetching a json response from an api - react.js


我目前正在嘗試從我的 api 的響應中獲取 jwt-token。
響應如下所示:

{
    "message": "Auth successful",
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6IlRvbUB0b20uZGUiLCJ1c2VySWQiOiI1ZGZiZTdiMWI3OTZkOTU4NzBiMGM4M2MiLCJpYXQiOjE1NzkyODg1NjYsImV4cCI6MTU4MTk2Njk2Nn0.7EmFE1D7wwqysPNkMMwiiw447TZiXy3kkqsXbyF1fDc"
}

現在我正在嘗試從該函數的響應中獲取令牌:

_signInAsync = async() => {

    if(this.state.email !== '' && this.state.password!== ''){

      fetch('http://192.168.2.60:4563/login', {
        method: 'POST',
        headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          email: this.state.email,
          password: this.state.password,
        }),
      })
      .then((response) => {
        if(response.ok){

          console.log(this.state.email);
          this.props.navigation.navigate('Main');
        }
      })
    }
  };

_signInAsync 函數是通過我創建的按鈕調用的。 在用不同的方法嚴重嘗試后,我想不出正確的方法,所以現在我希望得到你的幫助!

來自柏林的問候!

嘿德國人!

如果要獲取 JSON,則需要先處理收到的數據。 將您的提取更改為更像這樣:

 fetch('http://192.168.2.60:4563/login', {
    method: 'POST',
    headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      email: this.state.email,
      password: this.state.password,
    }),
  })
  .then( res => res.json() )
  .then((data) => {
      console.log(data.token) // should print your token!
      this.props.navigation.navigate('Main');
  })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM