首先,我们需要创建一个Express应用,并安装相关的依赖。 1. 创建一个新的文件夹,并在终端中进入该文件夹。 2. 执行以下命令来初始化一个新的package.json文件: ``` npm init -y ``` 3. 安装express和mysql模块: ``` npm install express mysql --save ``` 接下来,我们可以创建一个名为app.js的文件,并实现数据查询接口。 ```javascript const express = require('express'); const mysql = require('mysql'); const app = express(); // 创建与MySQL数据库的连接 const connection = mysql.createConnection({ host: 'localhost', user: 'root', password: 'password', database: 'database_name' // 替换为你的数据库名 }); // 连接到MySQL数据库 connection.connect(err => { if (err) { console.error('数据库连接失败:', err); return; } console.log('成功连接到数据库'); }); // 处理跨域访问 app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE'); res.header('Access-Control-Allow-Headers', 'Content-Type'); next(); }); // 查询接口 app.get('/data', (req, res) => { const id = req.query.id; // 获取参数中的id const name = req.query.name; // 获取参数中的name let query = 'SELECT * FROM table_name'; if (id) { query += ` WHERE id = ${id}`; } else if (name) { query += ` WHERE name LIKE '%${name}%'`; } // 执行SQL查询 connection.query(query, (err, results) => { if (err) { console.error('查询失败:', err); res.status(500).json({ error: '查询失败' }); return; } res.json(results); }); }); // 启动服务器 app.listen(3000, () => console.log('服务器已启动,监听端口:3000')); ``` 其中,需替换`localhost`、`root`、`password`、`database_name`和`table_name`为你的数据库相关信息。 需要创建一个数据表,可以使用以下SQL语句创建一个示例的数据表: ```sql CREATE TABLE table_name ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255) ); INSERT INTO table_name (name) VALUES ('John Doe'), ('Jane Smith'), ('Bob Johnson'); ``` 将上述SQL语句保存为一个`.sql`文件,如`data_table.sql`。 在终端中执行以下命令启动服务器: ``` node app.js ``` 现在,你可以通过以下接口来查询数据: ``` http://localhost:3000/data?id=1 ``` 或 ``` http://localhost:3000/data?name=John ``` 你将会得到符合查询条件的数据的JSON格式的响应。 [2024-12-08 14:44:44 | AI写代码神器 | 1529点数解答]