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

如何在现有React代码中添加fetch 实现表单提交时调用REST API

问题根因
  • 你生成的查询参数不符合标准格式:当前代码直接把输入值拼接到URL后,缺少参数名,标准查询参数结构为?参数名1=值1&参数名2=值2,后端无法识别无参数名的请求所以返回400。
  • 未对参数做URL编码:如果输入内容包含特殊字符(空格、中文、&等)会破坏URL结构,触发请求错误。
  • 受控组件配置不规范:input绑定的value初始值为undefined,会触发React警告,也可能导致表单取值异常。
修复后完整代码
const { useState } = React;

function Example() {
  // 初始化表单默认值,避免受控组件value为undefined
  const [form, setForm] = useState({
    one: '',
    two: ''
  });

  async function handleSubmit() {
    // 使用URLSearchParams自动构建标准查询字符串,自动处理编码
    const params = new URLSearchParams();
    params.append('one', form.one);
    params.append('two', form.two);
    const uri = `http://example.com/?${params.toString()}`;
    
    console.log(`Current state: ${JSON.stringify(form)}`);
    console.log(`Fetch URI: ${uri}`);

    try {
      // 完整fetch逻辑,根据API要求调整请求方法和头信息
      const response = await fetch(uri, {
        method: 'GET', // 如果是POST请求修改为POST,参数移到body中
        headers: {
          'Accept': 'application/json'
        }
      });
      
      if (!response.ok) {
        throw new Error(`请求错误: ${response.status}`);
      }
      
      const result = await response.json();
      console.log('请求成功', result);
      // 这里添加请求成功后的业务逻辑
    } catch (error) {
      console.error('请求失败', error);
      // 这里添加错误提示逻辑
    }
  }

  function handleChange(e) {
    const { nodeName, name, value } = e.target;
    if (nodeName === 'INPUT') {
      setForm({ ...form, [name]: value });
    }
  }

  return (
    <form onChange={handleChange}>
      <fieldset>
        <legend>Input one</legend>
        <input name="one" value={form.one} />
      </fieldset>
      <fieldset>
        <legend>Input two</legend>
        <input name="two" value={form.two} />
      </fieldset>
      <button type="button" onClick={handleSubmit}>Submit</button>
    </form>
  );
};

ReactDOM.render(
  <Example />,
  document.getElementById('react')
);
注意事项
  • 如果你的API要求POST请求,不要把参数拼在URL上,调整fetch配置如下:
    const response = await fetch('http://example.com', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      body: JSON.stringify(form)
    });
    
  • 若存在跨域问题,需要后端配置CORS响应头,不要在前端强行关闭安全限制。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 22:36:06