如何将React下拉框选中值POST提交到Node.js后端并正常获取
React下拉框值传递到Node.js后端修正方案
React端修改
原有问题点:
- 未给
handleSubmit绑定this指向,触发提交时会出现this指向异常 - axios POST请求放在
componentDidMount生命周期,组件加载时就会发送,此时用户还未选择下拉框值,model为空 - 子元素
option重复绑定了onChange事件,外层select已经绑定过handleChange,冗余可删除 handleSubmit中未实现提交选中值的逻辑,仅做了打印
修改后完整代码:
import React from 'react' import axios from 'axios' export default class Inference extends React.Component { constructor(props) { super(props); this.state = { model: "", options: [ { label: "Cat", value: "cat" }, { label: "Traffic", value: "traffic" }, { label: "Dog", value: "dog" }, ], }; // 绑定两个方法的this指向 this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleChange(e) { this.setState({ model: e.target.value }); console.log("Model Selected!!", e.target.value); } handleSubmit(event) { event.preventDefault(); // 点击提交时发送POST请求 axios.post('http://localhost:5000/getmodel', { model: this.state.model, }) .then((res) => { console.log("后端返回结果:", res.data); }) .catch(err => { console.error("请求出错:", err); }) } render() { const { options } = this.state; return ( <div className="container"> <div className="row"> <div className="col-6" style={{ paddingBottom: "100px", paddingTop: "20px", alignItems: "center", }} > <label className="" style={{ paddingTop: "5px", marginTop: "40px" }} > Model <form onSubmit={this.handleSubmit}> <select className="custom-select" name="example" value={this.state.model} onChange={this.handleChange} style={{ paddingTop: "5px", marginTop: "10px" }} > <option value="">--Select--</option> {options.map((option) => ( <option key={option.value} value={option.value}> {option.label} </option> ))} </select> <button type="submit" className="btn btn-success" style={{ marginTop: "100px" }} > Inference </button> </form> </label> </div> </div> </div> ); } }
Node端修改
原有问题点:
- 未配置JSON解析中间件,直接读
req.body会得到undefined - POST接口未返回响应,前端请求会超时报错
- 未配置跨域中间件,前后端端口不同时会出现跨域错误
修改步骤:
- 先安装依赖:
npm install express cors - 完整代码如下:
const express = require('express'); const cors = require('cors'); const app = express(); const port = 5000; // 配置跨域 app.use(cors()); // 配置JSON请求体解析中间件,必须写在路由前面 app.use(express.json()); // 配置表单格式请求体解析,可选配置 app.use(express.urlencoded({ extended: true })); app.post('/getmodel', (req, res) => { // 打印前端传过来的model值 console.log("收到的模型值:", req.body.model); // 给前端返回响应 res.json({ code: 200, msg: "接收成功", receivedModel: req.body.model }) }); app.get('/', function (req, res) { res.send('服务正常运行'); }) app.listen(port, () => { console.log(`服务运行在http://localhost:${port}`); })
内容的提问来源于stack exchange,提问作者Karthikeyan M
相关产品推荐
相关产品推荐

