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

我的文件夹结构如下所示:

http://img2.mukewang.com/634128ef0001974b04050172.jpg

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;

包.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 的数据不会显示在浏览器中。我需要帮助来理解为什么会这样。感谢您的关注并原谅我糟糕的英语。


米琪卡哇伊
浏览 76回答 2
2回答

红糖糍粑

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 dataapp.use(express.json());// create a GET routeapp.get('/express_backend', (req, res) => {&nbsp; //generate output in `json` format rather than `send`.&nbsp; 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 runningapp.listen(port, () => console.log(`Listening on port ${port}`));

守着一只汪

感谢您的关注。随着文件夹结构的变化(在根目录中创建一个名为“backend”的新文件夹,然后将文件“server.js”移动到该文件夹中),代码现在可以工作了。谢谢 -
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript