要部署React(Create-React-App)、Express.js和MySQL,您可以按照以下步骤进行操作:
创建React应用程序:
npx create-react-app my-app
cd my-app
my-app
的新React应用程序。创建Express.js服务器:
在React应用程序的根目录中,使用以下命令创建一个新的Express.js服务器:
npm init -y
npm install express mysql
这将创建一个新的package.json
文件,并在依赖项中安装Express.js和MySQL模块。
创建一个新的server.js
文件,并将以下代码添加到文件中:
const express = require('express');
const mysql = require('mysql');
const app = express();
// 创建MySQL连接
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'your_mysql_password',
database: 'your_database_name'
});
// 连接到MySQL数据库
connection.connect((err) => {
if (err) {
console.error('Error connecting to MySQL database: ', err);
} else {
console.log('Connected to MySQL database!');
}
});
// 创建API端点
app.get('/api/data', (req, res) => {
// 查询MySQL数据库中的数据
connection.query('SELECT * FROM data', (err, results) => {
if (err) {
console.error('Error querying data from MySQL database: ', err);
res.status(500).send('Error querying data from MySQL database');
} else {
res.json(results);
}
});
});
// 服务器监听端口
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
部署应用程序:
在React应用程序的根目录中,打开终端并运行以下命令来构建React应用程序:
npm run build
这将在build
目录中创建一个优化过的生产版本的React应用程序。
创建一个新的目录(例如server
),将build
目录中的所有文件复制到其中。
将server.js
文件移动到server
目录中。
在server
目录中,打开终端并运行以下命令来启动Express.js服务器:
node server.js
这将在本地主机上的默认端口(通常为http://localhost:5000
)上启动Express.js服务器。
测试应用程序:
http://localhost:5000/api/data
来测试API端点是否正常工作。这样,您就成功地部署了React(Create-React-App)、Express.js和MySQL应用程序。您可以根据自己的需求在React应用程序中使用API端点来加载和显示数据。