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);
  }
});
相关推荐
HDO清风18 小时前
CASIA-HWDB2.x 数据集DGRL文件解析(python)
开发语言·人工智能·pytorch·python·目标检测·计算机视觉·restful
AIFQuant21 小时前
如何利用免费股票 API 构建量化交易策略:实战分享
开发语言·python·websocket·金融·restful
Irene19912 天前
HTTP 请求方法选择与 RESTful 实践(对比 GraphQL、RPC)
rpc·restful·http请求·grpc·graphql
2501_921649493 天前
2026 如何快速选择股票、外汇金融行情数据 API
后端·python·websocket·金融·restful
卓码软件测评3 天前
【第三方双重资质软件测试机构:测试RESTful API和SOAP Web Services:LoadRunner协议选择和脚本编写】
测试工具·ci/cd·性能优化·单元测试·测试用例·restful
淡泊if4 天前
RESTful API设计标准:单体 vs 微服务的最佳实践
后端·微服务·restful
小二·4 天前
Go 语言系统编程与云原生开发实战(第3篇):企业级 RESTful API 开发 —— 中间件、验证、文档与权限控制
云原生·golang·restful
码农幻想梦6 天前
实验九 Restful和ajax实现
后端·ajax·restful
AIFQuant7 天前
如何通过股票数据 API 计算 RSI、MACD 与移动平均线MA
大数据·后端·python·金融·restful