5

I have a oauth set up. But when I want to get the access token with the fetch() function it just returns an object with things like _bodyInit, _bodyBlob and headers. So I just cannot get a JSON object. I'm on Android if that matters in any way.

Code:

componentDidMount() {
Linking.getInitialURL().then(url => {
      if(url) {
        console.log(url);
        const queries = url.substring(16)
        const dataurl = qs.parse(queries);
        if(dataurl.state === 'ungessable15156145640!') {
          console.log(dataurl.code);
          console.log(dataurl.state);
          return code = dataurl.code;
        }
      }
    }).then((code) => {
      fetch(`https://dribbble.com/oauth/token`, {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          'client_id': 'MY_ID',
          'client_secret': 'MY_SECRET',
          'code': code
        })
      })
      .then((res) => {
        var access_token = res;
        console.log(access_token);
      });
    });
  }

1 Answer 1

7

You almost got it right, you are missing one step though!

fetch doesn't return a json object, it returns a Response object, in order to get the json object, you have to use res.json()

fetch(`https://dribbble.com/oauth/token`, {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          'client_id': 'MY_ID',
          'client_secret': 'MY_SECRET',
          'code': code
        })
      })
      .then((res) => {
        return res.json();
      })
      .then((json) => {
         console.log(json); // The json object is here
      });

It's a good practice to add a catch just in case something goes wrong.

.then((json) => {
      console.log(json); // The json object is here
 });
.catch((err) => {
     // Handle your error here.
})
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.