我的文件夹结构如下所示:
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 的数据不会显示在浏览器中。我需要帮助来理解为什么会这样。感谢您的关注并原谅我糟糕的英语。
红糖糍粑
守着一只汪
相关分类