我可以使用fetch in react发布文本数据

问题描述 投票:-4回答:1

我正在使用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获取文本值

我收到错误了

未捕获的承诺typeError无法获取

javascript node.js reactjs
1个回答
0
投票

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

还要考虑在出现错误时为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) });
© www.soinside.com 2019 - 2024. All rights reserved.