简体   繁体   中英

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". 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 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 . 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 components state and displayed on screen?

Thanks!

response 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 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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM