【问题标题】:fetch success returns a promise获取成功返回一个承诺
【发布时间】:2020-04-13 09:46:46
【问题描述】:

我已经实现了一个外部 API 函数以在单击按钮时返回 text/html。但似乎没有返回数据。而是返回一个承诺。

<TouchableOpacity onPress={() => getData() }>
  <Text style={styles.button}>Register</Text>
</TouchableOpacity>

获取函数

const getData= () => {
    let formData = new FormData();
    formData.append("name", 'ABC');
    formData.append("age", 35)
    fetch(API_URL, {
      method: 'POST',
      body: formData,
    }).then(response => {
      console.log('success');
      console.log(JSON.stringify(response.text()))
    }).catch(error => {
      console.log('error');
      console.error(JSON.stringify(response));
    })
}

我只想要 html/文本响应

【问题讨论】:

  • response.text() 一个承诺。 (a)等待它也被解决

标签: reactjs react-native fetch


【解决方案1】:

您需要先处理response.JSON

const getData= () => {
    let formData = new FormData();
    formData.append("name", 'ABC')
    formData.append("age", 35)
    fetch(API_URL, {
      method: 'POST',
      body: formData,
    })
    .then(response => response.json())
    .then(response => {
      console.log(response)
    })
    .catch(error => {
      console.log('error')
    })
}

查看this documentation了解更多详情。

【讨论】:

    猜你喜欢
    • 2015-11-27
    • 2015-06-05
    • 1970-01-01
    • 1970-01-01
    • 2020-07-11
    • 1970-01-01
    • 2022-09-23
    • 1970-01-01
    • 2016-09-18
    相关资源
    最近更新 更多