没有带fetch()的JSON对象

Ded*_*pul 3 javascript react-native fetch-api

我设置了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);
      });
    });
  }
Run Code Online (Sandbox Code Playgroud)

QoP*_*QoP 5

您几乎完全正确,但是您还缺少一步!

fetch不返回json对象,它返回一个Response对象,为了获取json对象,您必须使用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
      });
Run Code Online (Sandbox Code Playgroud)

这是一个好习惯,以防万一出问题了。

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