admin管理员组文章数量:1025482
I have a simple react ponent and express endpoint that returns the string "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.
My ponent:
class App extends Component {
constructor(props) {
super(props);
this.state = {
data: null
};
}
ponentDidMount() {
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">Wele 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
. When I just use response
nothing happens and the text just shows up as "there is no data" since the state is empty.
How can I get the text from my endpoint into the ponents state and displayed on screen?
Thanks!
I have a simple react ponent and express endpoint that returns the string "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.
My ponent:
class App extends Component {
constructor(props) {
super(props);
this.state = {
data: null
};
}
ponentDidMount() {
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">Wele 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
. When I just use response
nothing happens and the text just shows up as "there is no data" since the state is empty.
How can I get the text from my endpoint into the ponents state and displayed on screen?
Thanks!
Share Improve this question asked Mar 13, 2019 at 13:51 intAintA 2,73115 gold badges48 silver badges72 bronze badges 2- how the response look like? – brk Commented Mar 13, 2019 at 13:53
- 1 you send from the backend a text no a jsonfile... so const body = await response.json(); give you an error try to send json file as res.send({file:'sample data'}); – Angelotti Commented Mar 13, 2019 at 14:05
3 Answers
Reset to default 4response
is a Response
object. 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.
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. In this case, you'll also need to amend your setState
and Error
, as body
will just be a string, not an object.
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.
My guess is that your endpoint does not have the res.data
in the response.
I would remend 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.
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
const body = await response.json();
you have that error.
so you can change your back-end and send Json object as
app.get('/sampleData', function(req, res) {
res.send({text:'sample data'});
});
or as Joe Clay had suggest you, you can receive text with
const body = await response.text();
I have a simple react ponent and express endpoint that returns the string "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.
My ponent:
class App extends Component {
constructor(props) {
super(props);
this.state = {
data: null
};
}
ponentDidMount() {
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">Wele 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
. When I just use response
nothing happens and the text just shows up as "there is no data" since the state is empty.
How can I get the text from my endpoint into the ponents state and displayed on screen?
Thanks!
I have a simple react ponent and express endpoint that returns the string "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.
My ponent:
class App extends Component {
constructor(props) {
super(props);
this.state = {
data: null
};
}
ponentDidMount() {
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">Wele 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
. When I just use response
nothing happens and the text just shows up as "there is no data" since the state is empty.
How can I get the text from my endpoint into the ponents state and displayed on screen?
Thanks!
Share Improve this question asked Mar 13, 2019 at 13:51 intAintA 2,73115 gold badges48 silver badges72 bronze badges 2- how the response look like? – brk Commented Mar 13, 2019 at 13:53
- 1 you send from the backend a text no a jsonfile... so const body = await response.json(); give you an error try to send json file as res.send({file:'sample data'}); – Angelotti Commented Mar 13, 2019 at 14:05
3 Answers
Reset to default 4response
is a Response
object. 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.
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. In this case, you'll also need to amend your setState
and Error
, as body
will just be a string, not an object.
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.
My guess is that your endpoint does not have the res.data
in the response.
I would remend 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.
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
const body = await response.json();
you have that error.
so you can change your back-end and send Json object as
app.get('/sampleData', function(req, res) {
res.send({text:'sample data'});
});
or as Joe Clay had suggest you, you can receive text with
const body = await response.text();
本文标签: javascriptHow do I get data from Express endpoint in a React componentStack Overflow
版权声明:本文标题:javascript - How do I get data from Express endpoint in a React component? - Stack Overflow 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://it.en369.cn/questions/1745630201a2160114.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论