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

React Native中URLSearchParams替代方案咨询及请求报错问题

React Native中替代URLSearchParams发送x-www-form-urlencoded请求的方案

问题原因

React Native 中的 URLSearchParams 实现与 Web 端存在差异,导致序列化后的表单数据无法被服务器正确解析,进而返回500错误;而服务器返回的是HTML错误页面,这就是你遇到JSON Parse error: Unexpected token: <的核心原因——代码尝试将HTML内容解析为JSON。

替代方案:手动拼接URL编码的表单字符串

直接手动将键值对编码为符合application/x-www-form-urlencoded格式的字符串,完全避免依赖URLSearchParams:

修改后的完整代码

const handleSubmit = async (e) => {
  if (e) {
    e.preventDefault();
  }

  if (!recaptchaToken) {
    alert("Please verify that you're a human");
    return;
  }

  // 手动构建URL编码的表单数据
  const formBody = Object.entries({
    email: email,
    password: password,
    passwordCheck: passwordCheck,
    recaptcha: recaptchaToken,
    profile: "Unfinished"
  })
  .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
  .join('&');

  fetch("/register", {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: formBody,
  })
  .then((res) => {
    // 先检查响应状态,提前捕获HTTP错误
    if (!res.ok) {
      throw new Error(`请求失败,状态码:${res.status}`);
    }
    return res.json();
  })
  .then((data) => {
    console.log('data', data)
    if (data !== "Email already in use") {
      console.log("success");
    } else {
      setRegisterError("Cette adresse e-mail est déjà utilisée");
    }
  })
  .catch((err) => {
    console.log(err);
    setError("请求失败,请稍后重试");
  });
};

额外优化说明

  • 增加了响应状态检查,提前拦截500这类HTTP错误,避免无效的JSON解析操作
  • 简化了错误判断逻辑,移除冗余的条件分支

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 10:52:13