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

React Native Expo:如何通过Fetch的POST方法发送JSON数组

Hey,你的思路完全正确!我来帮你把这段用fetch() POST发送JSON数组的代码优化得更健壮,同时拆解几个关键细节,避免踩坑:

使用fetch() POST发送JSON数组的完整指南

核心要点先明确

  • 必须设置Content-Type: application/json请求头:告诉服务器你发送的是JSON格式的数据,否则服务器可能无法正确解析请求体。
  • 用JSON.stringify()转换数据:fetch的body参数不接受直接的JS对象/数组,必须转成JSON字符串。
  • Accept: application/json是可选但推荐的:告诉服务器你期望返回JSON格式的响应,让交互更清晰。

基础优化版(基于你的示例)

把你的代码稍作调整,加上响应解析和更清晰的错误处理:

// 先定义你的JSON数组(可以是已有的变量)
const targetData = [
  { id: 1, name: 'aaa' },
  { id: 2, name: 'bbb' }
];

fetch("/echo/json/", {
  method: "POST",
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(targetData) // 把JS数组转为JSON字符串
})
.then(function(response) {
  // 注意:response只是响应对象,需要解析成JSON才能拿到实际数据
  return response.json();
})
.then(function(returnedData) {
  console.log('服务器返回的数据:', returnedData);
})
.catch(function(error) {
  console.error('请求遇到问题:', error);
});

更健壮的版本(包含HTTP错误处理)

fetch的特性是:只有网络错误才会触发.catch(),像404、500这类HTTP状态错误不会自动进入catch,所以我们需要手动判断响应状态:

const targetData = [
  { id: 1, name: 'aaa' },
  { id: 2, name: 'bbb' }
];

fetch("/echo/json/", {
  method: "POST",
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(targetData)
})
.then(function(response) {
  // 判断响应是否成功(状态码200-299)
  if (!response.ok) {
    throw new Error(`HTTP错误!状态码: ${response.status}`);
  }
  return response.json();
})
.then(function(returnedData) {
  console.log('成功获取返回数据:', returnedData);
})
.catch(function(error) {
  console.error('请求失败:', error.message);
});

更简洁的async/await写法

如果你的环境支持ES6+,用async/await会让代码逻辑更直观:

async function sendJsonArray() {
  const targetData = [
    { id: 1, name: 'aaa' },
    { id: 2, name: 'bbb' }
  ];

  try {
    const response = await fetch("/echo/json/", {
      method: "POST",
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(targetData)
    });

    if (!response.ok) {
      throw new Error(`HTTP错误!状态码: ${response.status}`);
    }

    const returnedData = await response.json();
    console.log('成功获取返回数据:', returnedData);
  } catch (error) {
    console.error('请求失败:', error.message);
  }
}

// 调用函数发送数据
sendJsonArray();

最后几个注意事项

  • 服务器端要配合:确保后端能正确解析JSON请求体,比如Node.js + Express需要用express.json()中间件,PHP需要用file_get_contents('php://input')获取请求体后再用json_decode()解析。
  • 跨域场景:如果请求的是不同域名的接口,服务器需要配置CORS,允许POST方法和Content-Type这类自定义请求头。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:47:44