
React Native 的 fetch API 要求 POST 请求的 body 必须是字符串(如 JSON 字符串)或 FormData,而不能直接传入 JavaScript 对象;遗漏 JSON.stringify() 是导致请求失败的常见原因。
react native 的 fetch api 要求 post 请求的 body 必须是字符串(如 json 字符串)或 formdata,而不能直接传入 javascript 对象;遗漏 `json.stringify()` 是导致请求失败的常见原因。
在 React Native 中调用后端 API 时,即使请求在 Postman 中能成功,也可能在客户端报错或返回 400/500 状态——这往往不是接口问题,而是请求体格式不合规所致。你提供的代码中,body: a 直接传入了一个 JS 对象,但 fetch 的 body 参数不接受原始对象,必须显式序列化为字符串。
✅ 正确写法如下(已修复关键问题,并增强健壮性):
const payload = {
ad: 'test',
telefon: 'test',
islem: 'test',
sube: 'test',
saat: 'test',
};
async function harrik() {
try {
const response = await fetch('https://localhost/api/test/cetran', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(payload), // ✅ 关键修复:必须 stringify
});
const result = await response.json(); // 推荐用 .json() 解析响应体
console.log('Success:', result);
} catch (error) {
console.error('Request failed:', error);
}
}⚠️ 注意事项:
-
localhost在真机上不可用:Android/iOS 模拟器或真机无法解析localhost(它指向设备自身)。请改用http://10.0.2.2:PORT(Android 模拟器)、http://127.0.0.1:PORT(部分场景),或更推荐——使用局域网 IP(如http://192.168.x.x:PORT)并确保后端允许跨域(CORS); - 避免混合
.then().catch()与async/await,统一使用try/catch更清晰、不易遗漏错误; - 始终检查
response.ok或状态码(如response.status === 200),避免仅依赖console.log(response)—— 它打印的是Response对象,而非实际数据; - 若后端要求其他认证头(如
Authorization),需一并添加到headers中。
总结:React Native 的 fetch 严格遵循 Web 标准,body 必须为字符串或 FormData;JSON.stringify() 不是可选项,而是必需步骤。同时,请务必验证网络环境与域名可达性——这是本地开发中最常被忽视的“隐形陷阱”。


















