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
相关产品推荐
相关产品推荐

