简体   繁体   中英

Fetch api response being undefined

This question has been asked but none of the answers helped.

In react native I'm making an api call with this:

  getAuthToken = () => {

  SecureStore.getItemAsync('authToken')
  .then((authToken) => {
    console.log(authToken);
    fetch('https://example.com?token=' + authToken + '&order_id=5480', {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      }
    }
)
})
.then(res => res.json())
.then(result => {
    console.log(result)
  })
.catch(error => {
    console.error(error);
})
}

In post man I can confirm this works: 在此处输入图片说明

However console.log(result) keeps returning as undefined. Any ideas what I'm doing wrong?

Your syntax is a bit off and your then block is not part of your fetch request. Update to the following and it should work

getAuthToken = () => {
  SecureStore.getItemAsync("authToken").then(authToken => {
    console.log(authToken);
    fetch("https://example.com?token=" + authToken + "&order_id=5480", {
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json"
      }
    })
      .then(res => res.json())
      .then(result => {
        console.log(result);
      })
      .catch(error => {
        console.error(error);
      });
  });
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM