简体   繁体   English

为什么我的 React-Express 应用程序无法从 express 后端获取和显示数据?

[英]Why my React-Express app can not fetch and display data from express backend?

My folder Structure look like this:我的文件夹结构如下所示:

在此处输入图像描述

The code inside of server.js: 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' });
});

The code inside of App.js (reside in client folder): 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: 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/"
}

I have run "node server.js" without error.我已经运行“node server.js”没有错误。 cd over to client directory and run "npm start" also without error. cd 到客户端目录并运行“npm start”也没有错误。 But, data from server.js doesn't displayed in the browser.但是,来自 server.js 的数据不会显示在浏览器中。 I need help to understand why that happened.我需要帮助来理解为什么会这样。 Thank you for your attention and forgive my poor english.感谢您的关注并原谅我糟糕的英语。

Server.js file requires some changes to server properly 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}`));

Thank you for your attention.感谢您的关注。 With folder structure change (make a new folder called "backend" in the root directory, then move the file "server.js" into inside this folder), the code is now working.随着文件夹结构的改变(在根目录中创建一个名为“backend”的新文件夹,然后将文件“server.js”移动到该文件夹内),代码现在可以工作了。 Thank you –谢谢 -

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在React-Express Node App中将对象从服务器发送到客户端组件 - How to send objects from server to client side components in react-express node app 如何从快速后端服务器获取图像并将其显示到 React Native 前端? - How to Fetch and Display an Image from an express backend server to a React Native frontend? 如何从快速后端服务器获取图像并将其显示到 React js 前端? - How to Fetch and Display an Image from an express backend server to a React js frontend? React Fetch 从 Express 后端返回错误的路由 - React Fetch Returning Wrong Route from Express Backend React 无法从 Express 获取数据 - React cannot fetch data from Express 如何从我的 express 应用程序获取数据到我的前端组件(在 React 中)? - How can I get data from my express app to my component in the frontend(which is in React)? 如何从 Express 后端服务器发送和获取数据 - how to send and fetch data from an express backend server 为什么我的反应应用程序和快速服务器之间的获取请求不起作用? - Why are my fetch requests between my react app and express server not working? 为什么我的节点快速应用无法从猫鼬获取数据? - Why is my node express app not fetching data from mongoose? 如何将数据从 React 前端 Hooks 传递到 Express 后端 - How to pass data from React front end Hooks to Express backend
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM