[英]How do I get data from Express endpoint in a React component?
I have a simple react component and express endpoint that returns the string "sample data". 我有一个简单的react组件,并表达了返回字符串“ sample data”的端点。 I'm just trying to hit that endpoint in my react app and store the text in state and display it on the screen.
我只是想在我的react应用程序中击中该端点并将文本存储在状态中并将其显示在屏幕上。
My component: 我的组件:
class App extends Component {
constructor(props) {
super(props);
this.state = {
data: null
};
}
componentDidMount() {
this.callBackendAPI()
.then(res => this.setState({ data: res.data }))
.catch(err => console.log(err));
}
async callBackendAPI() {
const response = await fetch('/sampleData');
const body = await response.json();
if(response.status !== 200) {
throw Error(body.message)
}
return body;
}
render() {
let data = this.state.data || 'there is no data';
return (
<div className="App">
<header className="App-header">
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">{data}</p>
</div>
);
}
}
export default (App);
The backend endpoint: 后端端点:
app.get('/sampleData', function(req, res) {
res.send('sample data');
});
I'm not sure I need response.json()
since the endpoint just returns plain text, I actually get an error with this code SyntaxError: Unexpected token s in JSON at position 0
. 我不确定我是否需要
response.json()
因为端点仅返回纯文本,所以我实际上收到了此代码SyntaxError: Unexpected token s in JSON at position 0
的错误SyntaxError: Unexpected token s in JSON at position 0
。 When I just use response
nothing happens and the text just shows up as "there is no data" since the state is empty. 当我只使用
response
什么都没有发生,并且由于状态为空,因此文本仅显示为“没有数据”。
How can I get the text from my endpoint into the components state and displayed on screen? 如何使文本从端点进入组件状态并显示在屏幕上?
Thanks! 谢谢!
response
is a Response
object. response
是一个Response
对象。 fetch
will give you access to it when the HTTP response header has been read, not the response body - this is why you have to await
on response.json()
, as you can't parse the body data until it has finished transferring. fetch
HTTP响应标头后 ,而不是响应正文, fetch
将为您提供访问权限,这是您必须await
response.json()
,因为您无法在正文数据传输完成之前解析正文数据。
This same principle applies when reading plain text from a Response
- you need to await
on response.text()
, to allow the response to finish being read. 从
Response
读取纯文本时,也应用相同的原理-您需要await
response.text()
,以使响应完成读取。 In this case, you'll also need to amend your setState
and Error
, as body
will just be a string, not an object. 在这种情况下,您还需要修改
setState
和Error
,因为body
只是一个字符串,而不是对象。
This might all seem a bit unintuitive, but it's for good reason - because you get a Response
as soon as the response starts being transferred, you can take actions based on the status/HTTP headers while the rest of the response is still loading. 这看起来似乎有点不直观,但这是有充分原因的-因为在响应开始传输后您会立即收到
Response
,因此您可以在状态其余部分仍加载的同时根据状态/ HTTP标头采取措施。
My guess is that your endpoint does not have the res.data
in the response. 我的猜测是您的端点在响应中没有
res.data
。
I would recommend throwing a console.log(res)
in your .then()
to see what is returned - if nothing is returned, I would double check you are returning on the url provided. 我建议在您的
.then()
抛出console.log(res)
来查看返回的内容-如果未返回任何内容,我将再次检查您是否在提供的url上返回。
Your code looks fine, I tested it quick and it looks good to me, it was just a matter of getting the response data correctly. 您的代码看起来不错,我对其进行了快速测试,对我来说也很好,这只是正确获取响应数据的问题。
I think your error is here: 我认为您的错误在这里:
app.get('/sampleData', function(req, res) {
res.send('sample data');
});
you send a text not a Json so when you try to receive data with 您发送的不是Json文本,因此当您尝试使用
const body = await response.json();
you have that error. 你有那个错误。
so you can change your back-end and send Json object as 因此您可以更改后端并将Json对象发送为
app.get('/sampleData', function(req, res) {
res.send({text:'sample data'});
}); });
or as Joe Clay had suggest you, you can receive text with 或如Joe Clay所建议的那样,您可以通过
const body = await response.text();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.