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

如何在React Native与Node.js(Express)之间传递数据

React Native 与 Express(Node.js) 数据交互实现方案

核心逻辑

React Native 与 Express 之间通过 HTTP/HTTPS 请求完成数据交互:Express 作为后端提供 API 接口,React Native 作为前端发送请求并处理响应。常用的前端请求工具是原生的 fetch 或第三方库 axios。


第一步:搭建 Express 后端接口

1. 基础 GET 接口(获取数据)

// Express 服务器文件(如 server.js)
const express = require('express');
const cors = require('cors');
const app = express();
const port = 3000;

app.use(cors());
app.use(express.json()); // 解析 JSON 请求体

// 示例:获取用户列表接口
app.get('/api/users', (req, res) => {
  // 可替换为数据库查询逻辑
  const mockUsers = [
    { id: 1, name: 'Alice', email: 'alice@example.com' },
    { id: 2, name: 'Bob', email: 'bob@example.com' }
  ];
  res.status(200).json(mockUsers);
});

app.listen(port, () => {
  console.log(`Server running on http://localhost:${port}`);
});

2. 基础 POST 接口(提交数据)

// 在 server.js 中添加 POST 接口
app.post('/api/users', (req, res) => {
  const newUser = req.body; // 获取前端发送的用户数据
  // 可添加数据库存储逻辑
  newUser.id = Date.now(); // 生成临时 ID
  res.status(201).json({
    message: '用户创建成功',
    user: newUser
  });
});

第二步:React Native 前端发送请求

1. 使用原生 fetch

GET 请求示例

// React Native 组件中
const fetchUsers = async () => {
  try {
    const response = await fetch('http://你的局域网IP:3000/api/users');
    if (!response.ok) throw new Error('请求失败');
    const users = await response.json();
    console.log('用户列表:', users);
    // 可将 users 存入组件状态
  } catch (error) {
    console.error('获取数据出错:', error.message);
  }
};

// 组件挂载时调用
useEffect(() => {
  fetchUsers();
}, []);

POST 请求示例

const createUser = async () => {
  const userData = {
    name: 'Charlie',
    email: 'charlie@example.com'
  };

  try {
    const response = await fetch('http://你的局域网IP:3000/api/users', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(userData)
    });
    if (!response.ok) throw new Error('提交失败');
    const result = await response.json();
    console.log('创建结果:', result);
  } catch (error) {
    console.error('提交数据出错:', error.message);
  }
};

2. 使用 axios(更简洁方案)

先在 React Native 项目中安装:

npm install axios

GET 请求示例

import axios from 'axios';

const fetchUsers = async () => {
  try {
    const response = await axios.get('http://你的局域网IP:3000/api/users');
    console.log('用户列表:', response.data);
  } catch (error) {
    console.error('获取数据出错:', error.response?.data?.message || error.message);
  }
};

POST 请求示例

const createUser = async () => {
  const userData = {
    name: 'Charlie',
    email: 'charlie@example.com'
  };
  try {
    const response = await axios.post('http://你的局域网IP:3000/api/users', userData);
    console.log('创建结果:', response.data);
  } catch (error) {
    console.error('提交数据出错:', error.response?.data?.message || error.message);
  }
};

关键注意事项

  • 跨域处理:必须在 Express 中使用 cors 中间件,否则 React Native 会因跨域限制无法请求接口。
  • 服务器地址:开发时不要用 localhost,模拟器/真机需使用电脑的局域网 IP(如 192.168.x.x)。
  • 错误处理:务必捕获网络异常、接口错误状态码等情况,避免应用崩溃。
  • 环境变量:建议将 API 地址存入环境变量,不要硬编码(如 React Native 用 process.env.EXPO_PUBLIC_API_URL,Express 用 process.env.PORT)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 01:13:02