最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - How do I get data from Express endpoint in a React component? - Stack Overflow

matteradmin4PV0评论

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
Add a ment  | 

3 Answers 3

Reset to default 4

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 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();
Post a comment

comment list (0)

  1. No comments so far