React与Express间MySQL查询及数据交互方法咨询
React + Express + MySQL 交互实现指南
核心原则:绝对不要从React直接传递完整SQL语句到Express,这会引发严重的SQL注入风险。正确做法是React传递业务参数,Express基于参数构建安全的参数化SQL查询。
1. 插入数据:React向Express传递参数
React通过POST请求将待插入数据放在请求体中,Express解析后使用参数化查询执行插入操作。
React 端代码(使用axios)
import axios from 'axios'; const insertUserData = async (newUser) => { try { // newUser 是包含字段的对象,如 {name: '张三', email: 'zhangsan@example.com'} const response = await axios.post('/api/users', newUser); console.log('插入成功:', response.data); } catch (error) { console.error('插入失败:', error); } }; // 调用示例 insertUserData({name: '张三', email: 'zhangsan@example.com'});
Express 端代码(使用mysql2)
const express = require('express'); const mysql = require('mysql2/promise'); const bodyParser = require('body-parser'); const app = express(); // 解析JSON请求体 app.use(bodyParser.json()); // 创建数据库连接池 const pool = mysql.createPool({ host: 'localhost', user: '你的数据库用户名', password: '你的数据库密码', database: '你的数据库名' }); // 插入数据接口 app.post('/api/users', async (req, res) => { const { name, email } = req.body; try { // 参数化查询(? 为占位符,避免SQL注入) const [result] = await pool.execute( 'INSERT INTO users (name, email) VALUES (?, ?)', [name, email] ); // 返回插入结果(如自增ID) res.json({ success: true, insertId: result.insertId }); } catch (err) { res.status(500).json({ success: false, error: err.message }); } }); app.listen(3001, () => console.log('Express服务运行在端口3001'));
2. 查询特定数据:React向Express传递查询参数
根据查询复杂度选择传递方式:简单查询用GET的URL查询参数,复杂多条件查询用POST请求体。
场景1:简单ID查询 - React端
const getUserById = async (userId) => { try { // 将ID放在URL查询参数中 const response = await axios.get(`/api/users?id=${userId}`); console.log('查询结果:', response.data); return response.data; } catch (error) { console.error('查询失败:', error); } }; // 调用示例 getUserById(1);
Express端对应接口
app.get('/api/users', async (req, res) => { const { id } = req.query; try { const [rows] = await pool.execute( 'SELECT * FROM users WHERE id = ?', [id] ); res.json({ success: true, data: rows }); } catch (err) { res.status(500).json({ success: false, error: err.message }); } });
场景2:多条件筛选 - React端
const searchUsers = async (filters) => { // filters 为多条件对象,如 {name: '张', email: 'example.com'} try { const response = await axios.post('/api/users/search', filters); console.log('筛选结果:', response.data); return response.data; } catch (error) { console.error('筛选失败:', error); } }; // 调用示例 searchUsers({name: '张', email: 'example.com'});
Express端对应接口
app.post('/api/users/search', async (req, res) => { const { name, email } = req.body; // 动态构建参数化查询 let sql = 'SELECT * FROM users WHERE 1=1'; const params = []; if (name) { sql += ' AND name LIKE ?'; params.push(`%${name}%`); } if (email) { sql += ' AND email LIKE ?'; params.push(`%${email}%`); } try { const [rows] = await pool.execute(sql, params); res.json({ success: true, data: rows }); } catch (err) { res.status(500).json({ success: false, error: err.message }); } });
3. Express返回结果至React展示
Express通过res.json()将数据库操作结果(成功状态、数据/错误信息)以JSON格式返回,React在请求回调中接收数据,更新组件状态后渲染页面。
React端接收并展示数据示例
import { useState, useEffect } from 'react'; import axios from 'axios'; function UserList() { const [users, setUsers] = useState([]); const [loading, setLoading] = useState(true); useEffect(() => { const fetchUsers = async () => { try { const response = await axios.get('/api/users'); setUsers(response.data.data); } catch (error) { console.error('获取用户列表失败:', error); } finally { setLoading(false); } }; fetchUsers(); }, []); if (loading) return <div>加载中...</div>; return ( <ul> {users.map(user => ( <li key={user.id}> {user.name} - {user.email} </li> ))} </ul> ); } export default UserList;
Express端返回逻辑说明
- 成功场景:用
res.json()返回包含success: true和数据的对象,如res.json({ success: true, data: rows }) - 失败场景:设置HTTP错误状态码(如500表示服务器内部错误),返回包含
success: false和错误信息的对象,如res.status(500).json({ success: false, error: err.message })
内容的提问来源于stack exchange,提问作者RLSoftwareDevelope
相关产品推荐
相关产品推荐

