如何将React下拉菜单选中值传递到NodeJS接口用于数据库查询?
实现方案
现有代码核心问题
- 后端接口未接收前端传递的查询参数,SQL预编译语法错误
- 前端未给查询按钮绑定请求逻辑,下拉值没有正确传递到后端
- dataset选中值未同步存入对应state字段
第一步:修改Node.js后端接口
首先安装cors包解决前后端跨域问题:
npm install cors
修改接口代码:
const cors = require('cors'); app.use(cors()); // 需放在所有路由定义之前 app.get('/model', (req,res)=>{ // 提取前端传递的查询参数 const { model, dataset } = req.query; // 预编译SQL的占位符?无需加引号,数据库会自动处理转义 const sql ="select * from new_schema.model_list,new_schema.images where model_name=? and dataset=?"; // 第二个参数传入和占位符顺序对应的参数数组 db.query(sql, [model, dataset], (err,results) =>{ if(err){ console.error('查询错误:', err); return res.status(500).json({msg: '查询失败'}); } console.log('查询结果:', results); res.send(results); }) })
第二步:修改React前端代码
1. 同步dataset选中值到state
修改handleChangeCourse方法,把选中的dataset值存入对应state字段:
handleChangeCourse = event => { this.setState({ course: event.target.value, dataset: event.target.value }); };
2. 新增查询请求方法
新增点击查询按钮触发的请求逻辑:
handleInference = () => { const { model, dataset } = this.state; // 非空校验 if(!model || !dataset || model === '--Select--' || dataset === '--Select--') { alert('请先选择Dataset和Model'); return; } // 发送带参数的请求到后端接口 axios.get('http://localhost:5000/model', { params: { model, dataset } }) .then(res => { console.log('后端返回结果:', res.data); // 可在此处把结果存入state,用于页面渲染 }) .catch(err => { console.error('请求失败:', err); }) }
3. 修复冗余代码、绑定按钮事件
- 删除model下拉框option上重复绑定的
onChange事件(select标签已经绑定了handleChange,不需要重复绑定) - 给Inference按钮绑定点击事件
// 下拉部分修改 {options.map((option) => ( <option value={option.value} key={option.value}>{option.label}</option> ))} // 按钮部分修改 <button type="button" className="btn btn-success" style={{marginTop:"100px"}} onClick={this.handleInference}>Inference</button>
内容的提问来源于stack exchange,提问作者Karthikeyan M
相关产品推荐
相关产品推荐

