没有带fetch()的JSON对象 [英] No JSON object with fetch()

查看:69
本文介绍了没有带fetch()的JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设置了oauth.但是,当我想使用fetch()函数获取访问令牌时,它只是返回一个带有_bodyInit,_bodyBlob和标头之类的对象.因此,我只是无法获取JSON对象.无论如何,我都在Android上.

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.

代码:

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);
      });
    });
  }

推荐答案

您几乎完全正确,但是您却缺少了一步!​​

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

fetch不返回json对象,而是返回一个Response对象,以获取 json对象,您必须使用res.json()

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.
})

这篇关于没有带fetch()的JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆