【问题标题】:Why my React-Express app can not fetch and display data from express backend?为什么我的 React-Express 应用程序无法从 express 后端获取和显示数据?
【发布时间】:2020-07-10 09:29:58
【问题描述】:

我的文件夹结构如下:

server.js 里面的代码:

const express = require('express');
const app = express();
const port = process.env.PORT || 5000;

// console.log that your server is up and running
app.listen(port, () => console.log(`Listening on port ${port}`));

// create a GET route
app.get('/express_backend', (req, res) => {
  res.send({ express: 'YOUR EXPRESS BACKEND IS CONNECTED TO REACT' });
});

App.js 内的代码(位于客户端文件夹中):

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
state = {
    data: null
  };

  componentDidMount() {
      // Call our fetch function below once the component mounts
    this.callBackendAPI().then(res => this.setState({ data: res.express })).catch(err => console.log(err));
  }
    // Fetches our GET route from the Express server. (Note the route we are fetching matches the GET route from server.js
  callBackendAPI = async () => {
    const response = await fetch('/express_backend');
    const body = await response.json();

    if (response.status !== 200) {
      throw Error(body.message) 
    }
    return body;
  };

  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <p className="App-intro">{this.state.data}</p>
      </div>
    );
  }
}

export default App;

package.json:

{
  "name": "dtdc-inside",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1"
  },
  "proxy": "http://localhost:5000/"
}

我运行“node server.js”没有错误。 cd 到客户端目录并运行“npm start”也没有错误。 但是,来自 server.js 的数据不会显示在浏览器中。 我需要帮助来理解为什么会这样。感谢您的关注并原谅我糟糕的英语。

【问题讨论】:

    标签: javascript node.js reactjs express


    【解决方案1】:

    Server.js 文件需要对服务器进行一些适当的更改

    const express = require('express');
    const app = express();
    const port = process.env.PORT || 5000;
    
    //Optional: add this line to parse incoming data. In case you want to accept data
    app.use(express.json());
    
    // create a GET route
    app.get('/express_backend', (req, res) => {
    
      //generate output in `json` format rather than `send`.
      res.json({ express: 'YOUR EXPRESS BACKEND IS CONNECTED TO REACT' });
    });
    
    //execute your server after writing all logic.
    // console.log that your server is up and running
    app.listen(port, () => console.log(`Listening on port ${port}`));
    

    【讨论】:

    • 感谢您的回答。这个我试过了,还是不行。
    • 只需检查您的 componentDidMount 函数是否正常工作以及您的 json api 是否正在发送数据。对于 API 测试使用 PostMan 实用程序。
    • 如果此问题仍然存在,请告诉我。我将尝试创建一个演示应用程序。
    • 感谢您的关注。随着文件夹结构的改变(在根目录中创建一个名为“backend”的新文件夹,然后将文件“server.js”移动到该文件夹​​中),代码现在可以工作了。谢谢
    【解决方案2】:

    感谢您的关注。随着文件夹结构的变化(在根目录中创建一个名为“backend”的新文件夹,然后将文件“server.js”移动到该文件夹​​内),代码现在可以工作了。谢谢——

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 2020-06-11
      • 2021-07-01
      • 2016-09-11
      相关资源
      最近更新 更多