You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React表单POST请求问题:无法提交表单字段动态值

React表单POST请求无法提交动态值问题

我在处理React表单的POST请求时遇到问题:已通过浏览器网络面板确认POST请求可正常发送,但服务器仅能写入预定义的静态值,无法提交表单字段中的动态输入值,恳请帮忙排查。

注意事项

  • TestForm.js中,请求响应的console.log并未输出内容
  • 未收到任何错误提示
  • 请求可正常发送至服务器并写入Postgres数据库,终端输出如下
  • 在handleSubmit开头执行console.log(sauce)可正确显示第一个表单字段的输入值
  • GitHub仓库地址:https://github.com/Younion/new-app

React表单组件(TestForm.js)

function TestForm() {
  const [sauce, setSauce] = useState('');
  const [presentation, setPresentation] = useState('');

  const handleSubmit = (e) => { 
    e.preventDefault();
    fetch('http://jyh:3000', {
      method: 'POST',
      headers: {'Content-Type':'application/json'},
      body: JSON.stringify({
        "test_name": sauce,
        "test_sauce": presentation,
      }),
      }).then((res) => {
        console.log(res.json());
        return res.json();
      }).catch((err) => {
          console.log(err.message);
      });
    };

  return (
    <form onSubmit={handleSubmit}>
      <div className="color-section" id="reviewASauce">
        <div className="container-fluid">
          <h2>Review a Sauce</h2><br />
            Trying a sauce that is already in our database? Review it!
            <br />
            <br />
            <br />
            <h2>Sauce Name</h2>
          <Form.Label htmlFor="test_name">
            </Form.Label>
          <Form.Control
            type="text"
            id="test_name"
            aria-describedby="test_name"
            placeholder="Input the name of the sauce here."
            value={sauce}
            onChange={(e) => setSauce(e.target.value)}
          />
          <Form.Text id="test_name" muted>
          </Form.Text>

          <br />
          <br />

          <Form.Label htmlFor="test_sauce">
            </Form.Label>
          <Form.Control
            type="text"
            id="test_sauce"
            aria-describedby="test_sauce"
            placeholder="Input the name of the sauce here."
            value={presentation}
            onChange={(e) => setPresentation(e.target.value)}
          />
          <Form.Text id="test_sauce" muted>
          </Form.Text>
        
        <br />
        <br />

        <Button variant="dark" type="submit">
          Submit
        </Button>
        </div>
      </div>
    </form>
  );
}

export default TestForm;

服务器端index.js

app.post('/', async (req, res) => {
    await TestTable.create({
            test_name: "test_name",
            test_sauce: "test_sauce",
        }).then((data) => {
            console.log(data.toJSON());
        }).catch((err) => {
            console.log(err);
        });
    });

提交后终端输出内容

{
  id: 100,
  test_name: 'test_name',
  test_sauce: 'test_sauce',
  updatedAt: 2022-12-21T02:54:42.447Z,
  createdAt: 2022-12-21T02:54:42.447Z
}

我尝试过修改handleSubmit函数和app.post逻辑,但始终无法将TestForm.js中的表单数据传递至index.js。

前端表单展示


问题排查与解决

核心问题

服务器端代码没有读取前端发送的请求体数据,而是直接写入了静态字符串"test_name"和"test_sauce",这就是数据库始终存储静态值的原因。另外前端console.log(res.json())无输出,是因为res.json()返回的是Promise,需要通过.then()或await才能获取实际响应数据。

修复步骤

  1. 服务器端配置并读取请求体
    先确保Express服务器配置了解析JSON请求体的中间件,再从req.body中获取动态数据:

    // 在所有路由前添加JSON解析中间件
    app.use(express.json());
    
    app.post('/', async (req, res) => {
        try {
            // 从请求体提取前端发送的动态值
            const { test_name, test_sauce } = req.body;
            const data = await TestTable.create({
                test_name,
                test_sauce
            });
            console.log(data.toJSON());
            // 返回成功响应给前端
            res.status(201).json(data);
        } catch (err) {
            console.log(err);
            res.status(500).json({ error: err.message });
        }
    });
    

    注:移除了冗余的await+.then()混合写法,改用try/catch更清晰地处理异步错误。

  2. 修复前端console.log无输出问题
    修改请求响应的处理逻辑,等待Promise解析后再打印数据:

    .then((res) => {
        return res.json();
    }).then((data) => {
        // 此处获取到实际响应数据
        console.log(data);
    }).catch((err) => {
        console.log(err.message);
    });
    
  3. 验证数据传输是否正常
    可在服务器端app.post开头添加console.log(req.body),确认前端发送的JSON数据是否被正确接收。

额外优化建议

  • 区分两个表单字段的placeholder内容,避免用户混淆,比如第二个字段改为"Input presentation details here."
  • 增加表单输入验证逻辑,比如输入为空时阻止提交,提升用户体验

内容的提问来源于stack exchange,提问作者Younion Miller

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 20:10:52