[英]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.