ZerOS 前端集成指南

本指南为前端工程师提供与 ZerOS 后端 API 集成的说明。包括认证、API 端点、数据结构和最佳实践。

目录

入门指南

前提条件

在集成 ZerOS 之前,请确保您具备以下条件:

  1. ZerOS API 密钥(请联系您的系统管理员)
  2. 访问 ZerOS API 文档
  3. 了解您项目的前端框架(React、Vue、Angular 等)

基础 URL

所有 API 请求的基础 URL 为:

https://api.zeroscommunity.com/v1

环境配置

建议使用环境变量进行配置:

// 前端配置示例
const config = {
  API_BASE_URL: process.env.REACT_APP_API_BASE_URL || 'https://api.zeroscommunity.com/v1',
  API_KEY: process.env.REACT_APP_API_KEY,
  AUTH_TOKEN: localStorage.getItem('authToken')
};

认证

ZerOS 使用 JWT(JSON Web Tokens)进行认证。以下是实现方法:

1. 获取令牌

// 登录请求示例
async function login(username, password) {
  const response = await fetch(`${config.API_BASE_URL}/auth/login`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ username, password })
  });
  
  if (!response.ok) {
    throw new Error('登录失败');
  }
  
  const data = await response.json();
  localStorage.setItem('authToken', data.token);
  return data;
}

2. 使用令牌

// 认证请求示例
async function fetchProtectedData() {
  const token = localStorage.getItem('authToken');
  
  const response = await fetch(`${config.API_BASE_URL}/protected/resource`, {
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    }
  });
  
  if (!response.ok) {
    throw new Error('请求失败');
  }
  
  return response.json();
}

3. 刷新令牌

// 令牌刷新示例
async function refreshToken() {
  const refreshToken = localStorage.getItem('refreshToken');
  
  const response = await fetch(`${config.API_BASE_URL}/auth/refresh`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ refreshToken })
  });
  
  if (!response.ok) {
    throw new Error('令牌刷新失败');
  }
  
  const data = await response.json();
  localStorage.setItem('authToken', data.token);
  return data;
}

API 端点

核心端点

| 端点 | 方法 | 描述 | 需要认证 | |------|------|------|----------| | /auth/login | POST | 用户登录 | 否 | | /auth/register | POST | 用户注册 | 否 | | /auth/refresh | POST | 刷新认证令牌 | 否(需要刷新令牌)| | /users | GET | 获取所有用户列表 | 是 | | /users/:id | GET | 根据 ID 获取用户 | 是 | | /users/:id | PUT | 更新用户 | 是 | | /users/:id | DELETE | 删除用户 | 是 | | /products | GET | 获取所有产品列表 | 否 | | /products/:id | 根据 ID 获取产品 | 否 | | /developers | GET | 获取所有开发者列表 | 否 | | /services | GET | 获取所有服务列表 | 否 |

使用示例

// 获取产品列表
async function fetchProducts() {
  const response = await fetch(`${config.API_BASE_URL}/products`);
  if (!response.ok) {
    throw new Error('获取产品失败');
  }
  return response.json();
}

// 创建新用户(仅管理员)
async function createUser(userData) {
  const token = localStorage.getItem('authToken');
  
  const response = await fetch(`${config.API_BASE_URL}/users`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(userData)
  });
  
  if (!response.ok) {
    throw new Error('创建用户失败');
  }
  
  return response.json();
}

数据结构

用户对象

{
  "id": "12345",
  "username": "johndoe",
  "email": "john@example.com",
  "role": "user",
  "createdAt": "2026-01-01T00:00:00Z",
  "updatedAt": "2026-01-01T00:00:00Z"
}

产品对象

{
  "id": "12345",
  "name": "ZerOS 核心",
  "description": "ZerOS 核心产品",
  "features": [
    "高级性能优化",
    "直观的用户界面",
    "强大的安全措施"
  ],
  "price": 999.99,
  "createdAt": "2026-01-01T00:00:00Z",
  "updatedAt": "2026-01-01T00:00:00Z"
}

开发者对象

{
  "id": "12345",
  "name": "张三",
  "role": "首席开发工程师",
  "bio": "张老师有超过 10 年的软件开发经验",
  "avatar": "https://example.com/avatar.jpg",
  "createdAt": "2026-01-01T00:00:00Z"
}

错误处理

常见错误代码

| 状态码 | 描述 | 处理策略 | |--------|------|----------| | 400 | 请求错误 | 发送前验证输入 | | 401 | 未授权 | 重定向到登录页面 | | 403 | 禁止访问 | 显示访问被拒绝消息 | | 404 | 未找到 | 显示资源未找到消息 | | 500 | 服务器内部错误 | 显示通用错误消息 |

错误处理示例

function handleApiError(error) {
  if (error.response) {
    // 请求已发送,服务器返回的状态码不在 2xx 范围内
    switch (error.response.status) {
      case 401:
        // 重定向到登录
        localStorage.removeItem('authToken');
        window.location.href = '/login';
        break;
      case 403:
        // 显示访问被拒绝
        showErrorMessage('您没有权限访问此资源');
        break;
      case 404:
        // 显示未找到
        showErrorMessage('未找到请求的资源');
        break;
      default:
        // 显示通用错误
        showErrorMessage('发生错误,请稍后重试');
    }
  } else if (error.request) {
    // 请求已发送但未收到响应
    showErrorMessage('未收到服务器响应,请检查您的网络连接');
  } else {
    // 设置请求时发生错误
    showErrorMessage('发生错误,请稍后重试');
  }
}

性能优化

1. 缓存

实施客户端缓存以减少 API 调用:

// 简单缓存实现
const cache = {
  data: {},
  expires: {}
};

function getCachedData(key, expiration = 3600000) { // 默认 1 小时
  const now = Date.now();
  if (cache.data[key] && cache.expires[key] > now) {
    return cache.data[key];
  }
  return null;
}

function setCachedData(key, data, expiration = 3600000) {
  cache.data[key] = data;
  cache.expires[key] = Date.now() + expiration;
}

// 使用方法
async function fetchProducts() {
  const cached = getCachedData('products');
  if (cached) {
    return cached;
  }
  
  const response = await fetch(`${config.API_BASE_URL}/products`);
  if (!response.ok) {
    throw new Error('获取产品失败');
  }
  
  const data = await response.json();
  setCachedData('products', data);
  return data;
}

2. 分页

对大型数据集使用分页:

async function fetchUsers(page = 1, limit = 20) {
  const response = await fetch(`${config.API_BASE_URL}/users?page=${page}&limit=${limit}`);
  if (!response.ok) {
    throw new Error('获取用户失败');
  }
  return response.json();
}

3. 防抖和节流

对搜索输入实施防抖:

function debounce(func, wait) {
  let timeout;
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout);
      func(...args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
}

// 使用方法
const debouncedSearch = debounce(async (query) => {
  const results = await searchAPI(query);
  updateSearchResults(results);
}, 300);

// 绑定到输入事件
inputElement.addEventListener('input', (e) => {
  debouncedSearch(e.target.value);
});

测试

API 测试

在开发期间使用 Postman 或 Insomnia 等工具进行 API 测试。

前端测试

为 API 集成实施单元测试:

// 使用 Jest 和 Mock Service Worker 的测试示例
import { rest } from 'msw';
import { setupServer } from 'msw/node';
import { fetchProducts } from './api';

const server = setupServer(
  rest.get('https://api.zeroscommunity.com/v1/products', (req, res, ctx) => {
    return res(ctx.json([
      { id: 1, name: '产品 1' },
      { id: 2, name: '产品 2' }
    ]));
  })
);

beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

test('成功获取产品列表', async () => {
  const products = await fetchProducts();
  expect(products).toHaveLength(2);
  expect(products[0].name).toBe('产品 1');
});

部署

生产最佳实践

  1. 环境变量

    • 开发、预发布和生产环境使用不同的 API 端点
    • 切勿硬编码 API 密钥或密钥
  2. 安全性

    • 所有 API 请求使用 HTTPS
    • 实施适当的 CORS 配置
    • 验证所有用户输入
  3. 性能

    • 精简和打包 JavaScript
    • 使用 HTTP/2 或 HTTP/3
    • 实施 Service Worker 以支持离线功能
  4. 监控

    • 实施前端错误跟踪(例如 Sentry)
    • 监控 API 响应时间
    • 跟踪用户与 API 端点的交互

生产配置示例

// 生产配置
const config = {
  API_BASE_URL: process.env.REACT_APP_API_BASE_URL || 'https://api.zeroscommunity.com/v1',
  API_KEY: process.env.REACT_APP_API_KEY,
  ENVIRONMENT: process.env.NODE_ENV || 'development',
  ENABLE_LOGGING: process.env.NODE_ENV !== 'production'
};

// 日志工具
function log(message, level = 'info') {
  if (config.ENABLE_LOGGING) {
    console[level](message);
  }
}

更多资源


© 2026 ZerOS Community. 保留所有权利。

最后更新于: 2026-02-25 提出修改建议