RESTful API

复制代码
https://api.example.com                // 根路径

1. 获取资源列表

描述:获取所有用户信息。

方法:GET

URL:/api/users

响应:

复制代码
[
  { "id": 1, "name": "Alice" },
  { "id": 2, "name": "Bob" }
]

前端调用:

javascript 复制代码
fetch('https://api.example.com/api/users')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));
javascript 复制代码
axios.get('https://api.example.com/api/users')
  .then(response => console.log(response.data))
  .catch(error => console.error('Error:', error));
  • axios.get:发起一个GET请求。
  • .then(response => console.log(response.data)):
  • 请求成功时,response 是 Axios 返回的响应对象。
  • response.data 是服务器返回的实际数据。
  • .catch(error => console.error('Error:', error)):
  • 请求失败时,error 是 Axios 提供的错误对象。
  • error 包含了错误详情,例如网络错误、服务器返回的错误状态码等

优化错误处理

  • error 是 Axios 提供的错误对象,通常包含以下属性:
  • error.message:错误的描述信息。
  • error.response:如果服务器返回了响应(如 4xx 或 5xx 状态码),error.response 会包含响应的详细信息。
  • error.response.data:服务器返回的错误数据。
  • error.response.status:HTTP 状态码(如 404、500)。
  • error.response.headers:响应头。
  • error.request:如果请求已发出但没有收到响应(如网络错误),error.request 会包含请求的详细信息。

优化错误处理

为了更好地处理错误,可以根据 error.response 和 error.request 区分不同类型的错误:

javascript 复制代码
axios.get('https://api.example.com/api/users')
  .then(response => {
    // 请求成功,打印数据
    console.log('Data:', response.data);
  })
  .catch(error => {
    if (error.response) {
      // 服务器返回了错误状态码
      console.error('Server Error:', error.response.data);
      console.error('Status Code:', error.response.status);
    } else if (error.request) {
      // 请求已发出,但没有收到响应
      console.error('Network Error:', error.message);
    } else {
      // 其他错误
      console.error('Error:', error.message);
    }
  });
  • error 是 Axios 自动传递的参数,不需要显式定义。
  • error 对象包含详细的错误信息,可以通过 error.response 和 error.request 区分不同类型的错误。
  • 优化错误处理:根据错误类型(服务器错误、网络错误、其他错误)分别处理,提供更清晰的调试信息。

2. 获取单个资源

描述:获取指定ID的用户信息。

方法:GET

URL:/api/users/{id}

响应:

复制代码
{ "id": 1, "name": "Alice" }

前端调用:

javascript 复制代码
const userId = 1;
fetch(`https://api.example.com/api/users/${userId}`)
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));
javascript 复制代码
const userId = 1;
axios.get(`https://api.example.com/api/users/${userId}`)
  .then(response => console.log(response.data))
  .catch(error => console.error('Error:', error));

3. 创建资源

描述:创建一个新用户。

方法:POST

URL:/api/users

请求体:

复制代码
{ "name": "Charlie" }

响应

复制代码
{ "id": 3, "name": "Charlie" }

前端调用:

javascript 复制代码
const newUser = { name: 'Charlie' };
fetch('https://api.example.com/api/users', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify(newUser)
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));
javascript 复制代码
const newUser = { name: 'Charlie' };
axios.post('https://api.example.com/api/users', newUser)
  .then(response => console.log(response.data))
  .catch(error => console.error('Error:', error));

4. 更新资源

描述:更新指定ID的用户信息。

方法:PUT

URL:/api/users/{id}

请求体:

复制代码
{ "name": "Alice Smith" }

响应:

复制代码
{ "id": 1, "name": "Alice Smith" }

前端调用:

javascript 复制代码
const userId = 1;
const updatedUser = { name: 'Alice Smith' };
fetch(`https://api.example.com/api/users/${userId}`, {
  method: 'PUT',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify(updatedUser)
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));
javascript 复制代码
const userId = 1;
const updatedUser = { name: 'Alice Smith' };
axios.put(`https://api.example.com/api/users/${userId}`, updatedUser)
  .then(response => console.log(response.data))
  .catch(error => console.error('Error:', error));

5. 部分更新资源

描述:部分更新指定ID的用户信息。

方法:PATCH

URL:/api/users/{id}

请求体:

复制代码
{ "name": "Alice Johnson" }

响应:

复制代码
{ "id": 1, "name": "Alice Johnson" }

前端调用:

javascript 复制代码
const userId = 1;
const partialUpdate = { name: 'Alice Johnson' };
fetch(`https://api.example.com/api/users/${userId}`, {
  method: 'PATCH',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify(partialUpdate)
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));
javascript 复制代码
const userId = 1;
const partialUpdate = { name: 'Alice Johnson' };
axios.patch(`https://api.example.com/api/users/${userId}`, partialUpdate)
  .then(response => console.log(response.data))
  .catch(error => console.error('Error:', error));

6. 删除资源

描述:删除指定ID的用户。

方法:DELETE

URL:/api/users/{id}

响应:204 No Content

前端调用:

javascript 复制代码
const userId = 1;
fetch(`https://api.example.com/api/users/${userId}`, {
  method: 'DELETE'
})
  .then(response => {
    if (response.status === 204) {
      console.log('User deleted successfully');
    }
  })
  .catch(error => console.error('Error:', error));
javascript 复制代码
const userId = 1;
axios.delete(`https://api.example.com/api/users/${userId}`)
  .then(response => {
    if (response.status === 204) {
      console.log('User deleted successfully');
    }
  })
  .catch(error => console.error('Error:', error));

7. 过滤资源

描述:根据条件过滤用户列表。

方法:GET

URL:/api/users?name=Alice

响应:

复制代码
[
  { "id": 1, "name": "Alice" }
]

前端调用:

javascript 复制代码
const query = 'Alice';
fetch(`https://api.example.com/api/users?name=${query}`)
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));
javascript 复制代码
const query = 'Alice';
axios.get(`https://api.example.com/api/users?name=${query}`)
  .then(response => console.log(response.data))
  .catch(error => console.error('Error:', error));

8. 分页获取资源

描述:分页获取用户列表。

方法:GET

URL:/api/users?page=1&limit=10

响应:

复制代码
{
  "data": [
    { "id": 1, "name": "Alice" },
    { "id": 2, "name": "Bob" }
  ],
  "pagination": {
    "page": 1,
    "limit": 10,
    "total": 100
  }
}

前端调用:

javascript 复制代码
const page = 1;
const limit = 10;
fetch(`https://api.example.com/api/users?page=${page}&limit=${limit}`)
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));
javascript 复制代码
const page = 1;
const limit = 10;
axios.get(`https://api.example.com/api/users?page=${page}&limit=${limit}`)
  .then(response => console.log(response.data))
  .catch(error => console.error('Error:', error));

9. 嵌套资源

描述:获取指定用户的所有订单。

方法:GET

URL:/api/users/{userId}/orders

响应:

复制代码
[
  { "id": 101, "product": "Laptop" },
  { "id": 102, "product": "Phone" }
]

前端调用:

javascript 复制代码
const userId = 1;
fetch(`https://api.example.com/api/users/${userId}/orders`)
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));
javascript 复制代码
const userId = 1;
axios.get(`https://api.example.com/api/users/${userId}/orders`)
  .then(response => console.log(response.data))
  .catch(error => console.error('Error:', error));

10. 搜索资源

描述:搜索用户。

方法:GET

URL:/api/users/search?q=Alice

响应:

复制代码
[
  { "id": 1, "name": "Alice" }
]

前端调用:

javascript 复制代码
const searchQuery = 'Alice';
fetch(`https://api.example.com/api/users/search?q=${searchQuery}`)
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));
javascript 复制代码
const searchQuery = 'Alice';
axios.get(`https://api.example.com/api/users/search?q=${searchQuery}`)
  .then(response => console.log(response.data))
  .catch(error => console.error('Error:', error));

总结 :

(1)Fetch

  • Fetch API:使用 fetch 发起HTTP请求,处理响应和错误。
  • 异步处理:通过 .then() 和 .catch() 处理异步操作。
  • 请求配置:
  • method:指定HTTP方法(GET、POST、PUT、PATCH、DELETE)。
  • headers:设置请求头,如 Content-Type。
  • body:传递请求数据(JSON格式)。
  • URL参数:动态拼接URL参数(如 userId、query)。
  • 错误处理:捕获并处理网络错误或API返回的错误。

(2)Axios:

  • 语法简洁,支持Promise。
  • 自动转换JSON数据。
  • 支持请求和响应拦截器。
  • 提供更强大的错误处理能力。
通用配置:
  1. 可以设置全局默认配置,例如 baseURL:
javascript 复制代码
axios.defaults.baseURL = 'https://api.example.com';
  1. 可以设置请求头:
javascript 复制代码
axios.defaults.headers.common['Authorization'] = 'Bearer token';
错误处理
  • 使用 .catch() 捕获错误。
  • 可以通过 error.response 获取服务器返回的错误信息:
javascript 复制代码
.catch(error => {
  if (error.response) {
    console.error('Server Error:', error.response.data);
  } else {
    console.error('Network Error:', error.message);
  }
});
相关推荐
前端白袍13 小时前
代码规范:RESTful API 全面介绍
后端·restful·代码规范
福大大架构师每日一题2 天前
ragflow v0.25.4 版本更新:RESTful API 数据源连接器、Agent 标签管理、Widget 持久化、GPT-5.4 模型支持全面升级
网络·gpt·restful
ZengLiangYi2 天前
用 ChatCrystal 学 Fastify:从零搭建 REST API
restful·express
taocarts_bidfans3 天前
Taoify开放接口全解析:RESTful架构下,跨境开发者多系统对接实操指南
大数据·架构·restful·跨境电商·独立站
清水白石0083 天前
在 RESTful、RPC 与事件驱动之间做选择:高频内部调用与审计回放场景下的架构取舍
rpc·架构·restful
weixin199701080165 天前
[特殊字符] RESTful API 接口规范详解:构建高效、可扩展的 Web 服务(附 Python 源码)
前端·python·restful
码以致用8 天前
FastAPI 从入门到实践:构建规范的 RESTful API 服务
后端·restful·fastapi
若阳安好8 天前
【备忘录】正则表达式
后端·正则表达式·restful
AIFQuant11 天前
贵金属 API 避坑:黄金/白银行情接口常见陷阱(数据漂移、断点、延迟)
开发语言·python·websocket·金融·restful·贵金属
想你依然心痛13 天前
HarmonyOS 6(API 23)实战:打造“看见设计“的AR工业设计评审系统——基于Face AR情绪反馈 + Body AR手势操控的沉浸光感协作平台
ar·restful·harmonyos·悬浮导航·沉浸光感