跨平台 HTTP 客户端:Request 库使用指南

Request 库:简化 Web 和 React Native 的 HTTP 请求

@swiftcarrot/request 提供了一个统一的 API,方便开发者在 Web 和 React Native 环境下进行 HTTP 请求。

安装

npm install @swiftcarrot/request

基本用法

import Request from '@swiftcarrot/request';

// 创建 Request 实例,设置基础 URL 和超时时间
const req = new Request('https://api.example.com/v1').timeout(5000);

// 发起 GET 请求
req.get('/articles', { page: 1 });

// 发起 POST 请求并处理登录 token
req.post('/login', { name: 'test', password: '123' })
  .then(({ token }) => req.token(token)); 

// 使用设置的 token 发起 POST 请求
req.post('/articles', { title: 'test' });

//  发起 DELETE 请求并清除 token
req.delete('/logout')
  .then(() => req.token(null));

代码说明:

  • 通过 new Request() 创建实例,并设置基础 URL 和超时时间。
  • 使用 .get(), .post(), .delete() 等方法发起不同类型的请求。
  • 可以使用 .then() 处理响应数据。
  • 使用 .token() 方法设置和清除全局 token。
zip 文件大小:79.6KB