【问题标题】:Can i post text data using fetch in react我可以在反应中使用 fetch 发布文本数据吗
【发布时间】:2019-02-05 05:52:09
【问题描述】:

我正在使用react js,我想发布文本并返回文本。

谁能帮助我发布文本和接收文本?我用过了 content type text/plain 但这没有帮助。

有什么办法吗?

const options = {
    method: "POST",
    headers: {
        "Content-Type": "text/plain"
    },
    body: this.state.url
}

fetch("http://localhost:3000/messages", options)
    .then(response => response)
    .then(data => {
        console.log(data)
        this.setState({
            code: data
        });
    });

这是我尝试从 api 获取文本值的内容

我收到一个错误

Uncaught promise typeError 获取失败

【问题讨论】:

  • 发到哪里?从什么获得?你想做什么?
  • 请在您的问题中更具体。
  • 阅读 github.com/axios/axios 以进行 api 调用

标签: javascript node.js reactjs


【解决方案1】:

fetch 为 Response 对象返回一个“promise”,该对象具有 json、text 等的 promise 创建者,具体取决于内容类型。所以代码应该改成。

还可以考虑为 promise 添加一个 catch 块,以防出现错误并检查控制台输出错误(如果有)。

const options = {
    method: "POST",
    headers: {
        "Content-Type": "text/plain"
    },
    body: this.state.url
}

fetch("http://localhost:3000/messages", options)
    .then(response => response.json()) // or response.text()
    .then(data => {
        console.log(data)
        this.setState({
            code: data
        });
    })
     .catch(err => { console.log('error while fetching', err) });

【讨论】:

    猜你喜欢
    • 2015-08-20
    • 2019-06-11
    • 2021-11-25
    • 2020-12-16
    • 2011-07-31
    • 2021-01-15
    • 1970-01-01
    • 2021-09-24
    • 2021-09-02
    相关资源
    最近更新 更多