gpt4 book ai didi

javascript - 从 express 后端获取后 react 未决的 promise

转载 作者:行者123 更新时间:2023-11-29 22:48:27 26 4
gpt4 key购买 nike

我有一个像这样的简单 node.js express 服务器:

const express = require('express');
const app = express();
const port = process.env.PORT || 5000;

app.listen(port, () => console.log(`Listening on port ${port}`));

app.get('/express_backend', (req, res) => {
res.send({ express: 'YOUR EXPRESS BACKEND IS CONNECTED TO REACT' });
});

并像这样在 package.json 中设置代理:

"proxy": "http://localhost:5000/"

但是,在我的 App.js 中,我尝试从服务器获取 JSON,但它返回给我一个未决的 promise (我通过 .then() 中的 console.log 发现了这一点)。我该如何解决这个问题,以便它正确地获取 express JSON 对象中的字符串?

class App extends Component {

constructor(){
super();
this.state = {data: "asdf"};
}

componentDidMount() {
fetch('/express_backend')
.then(res => this.setState({data: res.express}));
}

此时我正在运行 node server.jsnpm start

最佳答案

Here's一篇关于 fetch 如何返回数据的好文章。

The response of a fetch() request is a Stream object, which means that when we call the json() method, a Promise is returned since the reading of the stream will happen asynchronously.

所以你需要先调用json()方法,它返回一个promise。

fetch('/express_backend')
.then(res => {
if (!res.ok) {
throw new Error(res.statusText);
}
return res.json()
})
.then(res => this.setState({data: res.express}))
.catch(err => console.log(err));

关于javascript - 从 express 后端获取后 react 未决的 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57915728/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com