0

Hi,
I'm currently trying to fetch a jwt-token from a response from my api.
The response looks like this:

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

Now I'm trying to fetch the token out of that response in that function:

_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 function is called via a button I have created. After severel tries with different approaches I couldn't figure out the right way, so now I'm hoping for your help!

Greetings from Berlin!

2
  • Sorry, where do you attempt to fetch the token? I don't see anywhere the token is being referenced in the code. Commented Jan 17, 2020 at 19:33
  • Also, this is already an async function, don't subject yourself to needless callback nesting with .then() when you can just const response = await fetch(...) Commented Jan 17, 2020 at 19:34

1 Answer 1

1

Heyo German man!

If you want to fetch a JSON, you need to process the data you receive first. Change your fetch to look more like this:

 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');
  })
Sign up to request clarification or add additional context in comments.

Comments

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.