简体   繁体   English

如何在React组件中从Express端点获取数据?

[英]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. 在这种情况下,您还需要修改setStateError ,因为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.

相关问题 如何从我的 express 应用程序获取数据到我的前端组件(在 React 中)? - How can I get data from my express app to my component in the frontend(which is in React)? 如何从 Axios 获取数据并从 React 中的 Function 组件返回? - How do I get data from Axios and return it from a Function Component in React? 如何使用Express从一个端点发送多个查询? - How do I send multiple queries from one endpoint with Express? 我如何获取从另一个组件返回的数据 react js - How do i get data that return from another component react js 如何从 Express 中的 API 获取要在 Angular 中显示的数据? - How do I get data to display in Angular from API in Express? 如何从 React Img 组件中获取值 - How do I get the value from a React Img component 我如何在我的反应组件中访问表达参数 - how do I acces express params in my react component 每次单击按钮时如何从端点获取数据? 在反应中 - How do I fetch data from an endpoint everytime I click a button? In React 如何在 Express 中创建临时端点 - How Do I Create A Temporary Endpoint In Express 如何从 React Native 项目中从 WordPress API 端点获取的数据中删除 HTML 字符? - How do I remove HTML characters from the data fetched from a WordPress API endpoint in a React Native project?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM