摘要:本文了解了接口的概念和组成,以及什么是RESTful风格的接口。
环境
Windows 10 企业版 LTSC 21H2
Node 18.14.0
NPM 9.3.1
NVM 1.1.12
1 简介
在网络通信的场景中,接口是前后端通信的桥梁。前端将数据封装到请求里,根据请求路径访问后端提供的接口,接口在收到请求后会处理数据并生成结果,最终将结果返回给客户端。
在前后端沟通中常常将接口称为API(Application Program Interface)接口,通常由后端提供给前端和其他后端调用。
2 组成
2.1 请求地址
接口所在的资源路径,即URL地址。
2.2 请求方法
接口接受的请求类型。
常见的有四种:
- GET请求:这种类型的请求主要用于获取数据,对应查询操作。
- POST请求:这种类型的请求主要用于提交数据,对应增加操作。
- PUT请求:这种类型的请求主要用于更新数据,对应更新操作。
- DELETE请求:这种类型的请求主要用于删除数据,对应删除操作。
2.3 请求参数
接口需要的数据。
按参数所在位置不同,可以分为三种:
- 参数附加在请求地址后面。示例:
url1
| https://api.example.com/getData?id=1
|
- 参数附加在请求地址中。示例:
url1
| https://api.example.com/getData/1
|
- 参数附加在请求体中,通常使用JSON格式传递。示例:json
2.3.1 原生表单
原生表单的请求体为application/x-www-form-urlencoded
类型,页面中的form
元素的默认类型。
提交后会将数据通过键值对的形式传递,如果请求方法是GET请求会拼接到请求地址传输,如果请求方法是POST请求会通过请求体传输。
通过form
元素请求接口:
html1 2 3 4 5 6 7
| <form action="/info" method="post"> <div> <label for="username">用户名:</label> <input type="text" id="username" name="username"> </div> <button type="submit">提交</button> </form>
|
通过form
元素和AJAX请求接口:
html1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| <body> <form id="infoForm"> <div> <label for="username">用户名:</label> <input type="text" id="username" name="username"> </div> <button type="submit">提交</button> </form> </body> <script> $(document).ready(function () { $('#infoForm').on('submit', function (e) { e.preventDefault(); const formData = $(this).serialize(); $.ajax({ url: '/info', type: 'POST', data: formData, success: function (response) { console.log('Success:', response); }, error: function (xhr, status, error) { console.error('Error:', error); }, }); }); }); </script>
|
提交后浏览器会自动将请求头中的Content-Type
属性设置为application/x-www-form-urlencoded
类型。
2.3.2 复杂表单
复杂表单的请求体为multipart/form-data
类型,页面中form
元素的enctype
属性值设为multipart/form-data
类型。
提交后会将数据通过分段的形式传递,只在请求方法是POST请求的时候生效,主要用于处理文件上传。
通过form
元素请求接口:
html1 2 3 4 5 6 7 8 9 10 11
| <form action="/info" method="post" enctype="multipart/form-data"> <div> <label for="username">用户名:</label> <input type="text" id="username" name="username"> </div> <div> <label for="portrait">头像:</label> <input type="file" id="portrait" name="portrait"> </div> <button type="submit">提交</button> </form>
|
通过form
元素和AJAX请求接口:
html1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| <body> <form id="infoForm"> <div> <label for="username">用户名:</label> <input type="text" id="username" name="username"> </div> <div> <label for="portrait">头像:</label> <input type="file" id="portrait" name="portrait"> </div> <button type="submit">提交</button> </form> </body> <script> $(document).ready(function () { $('#infoForm').on('submit', function (e) { e.preventDefault(); const formData = new FormData(this); $.ajax({ url: '/info', type: 'POST', data: formData, processData: false, contentType: false, success: function (response) { console.log('Success:', response); }, error: function (xhr, status, error) { console.error('Error:', error); }, }); }); }); </script>
|
提交后浏览器会自动将请求头中的Content-Type
属性设置为multipart/form-data
类型,同时设置分段用到的分隔符。
2.3.3 原生数据
原生数据用于发送纯文本数据,需要手动设置数据类型,支持JSON/XML/HTML/TXT等格式,不能通过页面中form
元素提交,只能通过JS提交。
提交后会将数据通过JSON字符串的形式传递,只在请求方法是POST请求的时候生效,主要用于处理异步请求。
通过AJAX请求接口:
html1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| <body> <div> <label for="username">用户名:</label> <input type="text" id="username" name="username"> </div> <button id="submit">提交</button> </body> <script> $(document).ready(function () { $('#submit').on('click', function (e) { const data = { username: $('#username').val() }; const jsonData = JSON.stringify(data); $.ajax({ url: '/info', type: 'POST', data: jsonData, contentType: 'application/json', success: function (response) { console.log('Success:', response); }, error: function (xhr, status, error) { console.error('Error:', error); }, }); }); }); </script>
|
2.3.4 文件数据
文件数据用于发送二进制文件数据,用于上传文件,只能通过JS提交。
提交后会将数据通过二进制的形式传递,只在请求方法是POST请求的时候生效,主要用于处理文件上传。
通过AJAX请求接口:
html1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| <body> <div> <label for="portrait">头像:</label> <input type="file" id="portrait" name="portrait"> </div> <button id="submit">提交</button> </body> <script> $(document).ready(function () { $('#submit').on('click', function (e) { const formData = new FormData(); const fileInput = $('#portrait')[0]; formData.append('portrait', fileInput.files[0]); $.ajax({ url: '/info', type: 'POST', data: formData, processData: false, contentType: 'application/octet-stream', success: function (response) { console.log('Success:', response); }, error: function (xhr, status, error) { console.error('Error:', error); }, }); }); }); </script>
|
2.4 响应结果
接口处理数据后返回的结果。
通常包括三部分:
- 状态码:表示请求是否成功,比如200表示成功等。
- 响应头:包含额外信息,比如内容类型和编码等。
- 响应体:返回的具体数据,比如JSON格式的数据。
常见的状态码:
状态码 |
描述 |
含义 |
200 |
OK |
请求成功,返回数据。 |
301 |
Moved Permanently |
资源永久移动到新地址。 |
302 |
Found |
资源临时移动到新地址。 |
304 |
Not Modified |
资源未修改,使用缓存。 |
400 |
Bad Request |
请求格式错误。 |
401 |
Unauthorized |
请求未授权。 |
403 |
Forbidden |
服务器拒绝访问。 |
404 |
Not Found |
资源不存在。 |
500 |
Internal Server Error |
服务器内部错误。 |
502 |
Bad Gateway |
网关或代理收到无效响应。 |
503 |
Service Unavailable |
服务器暂时不可用。 |
总结:
- 2xx:成功类状态码,表示请求已正确处理。
- 3xx:重定向类状态码,表示资源位置已改变。
- 4xx:客户端错误类状态码,表示请求存在问题。
- 5xx:服务器错误类状态码,表示服务器无法处理请求。
3 RESTful
RESTful是一种特殊风格的接口,主要特点有如下几个:
- 接口的请求地址表示资源,路径中不能有动词,结尾不能使用
/
符号。
- 接口的请求方法要与接口的处理逻辑对应。
- 接口的响应结果要与状态码对应。
建议规范:
- 获取资源统一为
GET /resource-names/{recourceId}
地址。
- 复杂查询统一为
GET /resource-names?age=0,10&name=,姓&q=查询关键字&page=1&size=10
地址。
- 创建资源统一为
POST /resource-names
地址,请求参数通过请求体使用JSON格式传递。
- 删除资源统一为
DELETE /resource-names/{recourceId}
地址。
- 更新资源统一为
PUT /resource-names/{recourceId}
地址。
- 其他操作统一为
POST /resouce-names/{resourceId}/action-name
地址。
条