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

使用默认表单发POST请求后,如何获取Express的res.send返回值?

解决React表单默认提交后获取Express返回值的方法

默认表单提交会触发页面跳转/刷新,没法直接捕获后端响应,你可以用以下几种方式解决:

1. 阻止默认提交,改用Fetch/Axios发起请求

这是最常用的方案,能完全控制请求和响应流程:

  • 在表单的onSubmit事件里阻止默认行为
  • 手动收集表单数据,用Fetch或Axios发送POST请求,直接获取响应

示例代码:

import { useState } from 'react';

function MyForm() {
  const [formData, setFormData] = useState({
    username: '',
    password: ''
  });

  const handleSubmit = async (e) => {
    e.preventDefault(); // 阻止默认表单提交
    try {
      const response = await fetch('/submit-form', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(formData),
      });
      const result = await response.json(); // 假设后端返回JSON
      // 这里处理返回值,比如显示提示、更新状态
      console.log('后端返回:', result);
    } catch (error) {
      console.error('请求失败:', error);
    }
  };

  const handleChange = (e) => {
    setFormData({
      ...formData,
      [e.target.name]: e.target.value
    });
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        name="username"
        value={formData.username}
        onChange={handleChange}
        placeholder="用户名"
      />
      <input
        type="password"
        name="password"
        value={formData.password}
        onChange={handleChange}
        placeholder="密码"
      />
      <button type="submit">提交</button>
    </form>
  );
}

export default MyForm;

Express后端如果返回JSON,记得设置响应头:

app.post('/submit-form', (req, res) => {
  // 处理表单数据
  res.setHeader('Content-Type', 'application/json');
  res.send(JSON.stringify({ success: true, message: '提交成功' }));
});

2. 用隐藏iframe接收响应(不刷新页面)

如果必须保留默认表单提交的方式,可以把表单提交到隐藏的iframe里,然后监听iframe的加载事件获取响应:

示例代码:

import { useRef } from 'react';

function MyForm() {
  const iframeRef = useRef(null);

  const handleIframeLoad = () => {
    const iframeDoc = iframeRef.current.contentDocument || iframeRef.current.contentWindow.document;
    const responseText = iframeDoc.body.textContent;
    // 解析响应,比如转成JSON
    try {
      const result = JSON.parse(responseText);
      console.log('后端返回:', result);
    } catch (e) {
      console.log('后端返回文本:', responseText);
    }
  };

  return (
    <>
      <form
        action="/submit-form"
        method="POST"
        target="hidden-iframe" // 指定提交到iframe
      >
        <input type="text" name="username" placeholder="用户名" />
        <input type="password" name="password" placeholder="密码" />
        <button type="submit">提交</button>
      </form>
      <iframe
        name="hidden-iframe"
        ref={iframeRef}
        onLoad={handleIframeLoad}
        style={{ display: 'none' }}
      />
    </>
  );
}

export default MyForm;

这种方式不需要修改后端的返回逻辑,但处理灵活性不如Fetch方案。

3. 后端返回HTML页面(页面跳转)

如果可以接受页面跳转,后端直接返回包含响应内容的HTML页面,用户提交后会跳转到这个页面查看结果:

Express后端示例:

app.post('/submit-form', (req, res) => {
  // 处理表单数据
  res.send(`
    <html>
      <body>
        <h1>提交成功</h1>
        <p>返回内容:提交的数据已处理</p>
        <a href="/">返回首页</a>
      </body>
    </html>
  `);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 18:56:06