【问题标题】:No JSON object with fetch()没有带有 fetch() 的 JSON 对象
【发布时间】:2016-11-04 13:10:26
【问题描述】:

我设置了一个 oauth。但是,当我想使用 fetch() 函数获取访问令牌时,它只会返回一个包含 _bodyInit、_bodyBlob 和标头之类的对象。所以我无法获得 JSON 对象。如果这有任何影响,我在 Android 上。

代码:

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

【问题讨论】:

    标签: javascript react-native fetch-api


    【解决方案1】:

    你几乎做对了,但你少了一步!​​

    fetch不返回json对象,它返回一个Response对象,为了得到json object,你必须使用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
          });
    

    添加一个 catch 是一个很好的做法,以防出现问题。

    .then((json) => {
          console.log(json); // The json object is here
     });
    .catch((err) => {
         // Handle your error here.
    })
    

    【讨论】:

      猜你喜欢
      • 2015-06-10
      • 2015-01-28
      • 1970-01-01
      • 1970-01-01
      • 2023-02-15
      • 1970-01-01
      • 2012-08-22
      相关资源
      最近更新 更多