HTTP 请求方法
HTTP 常见请求方法及其用途
问题
HTTP 有哪些请求方法?各自的用途是什么?
解答
常用请求方法
| 方法 | 用途 | 幂等性 | 请求体 |
|---|---|---|---|
| GET | 获取资源 | 是 | 无 |
| POST | 创建资源 | 否 | 有 |
| PUT | 完整更新资源 | 是 | 有 |
| PATCH | 部分更新资源 | 否 | 有 |
| DELETE | 删除资源 | 是 | 可选 |
| HEAD | 获取响应头 | 是 | 无 |
| OPTIONS | 获取支持的方法 | 是 | 无 |
代码示例
// GET - 获取用户列表
fetch('/api/users')
.then(res => res.json())
// POST - 创建新用户
fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Tom', age: 20 })
})
// PUT - 完整替换用户信息
fetch('/api/users/1', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Tom', age: 21, email: 'tom@example.com' })
})
// PATCH - 只更新部分字段
fetch('/api/users/1', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ age: 22 })
})
// DELETE - 删除用户
fetch('/api/users/1', {
method: 'DELETE'
})
// HEAD - 只获取响应头,不返回响应体
fetch('/api/users', { method: 'HEAD' })
// OPTIONS - 预检请求,常用于 CORS
fetch('/api/users', { method: 'OPTIONS' })
PUT 与 PATCH 的区别
// 原始数据
{ id: 1, name: 'Tom', age: 20, email: 'tom@example.com' }
// PUT - 必须传完整数据,否则未传字段会丢失
PUT /api/users/1
{ name: 'Tom', age: 21 }
// 结果:{ id: 1, name: 'Tom', age: 21 } // email 丢失
// PATCH - 只更新传入的字段
PATCH /api/users/1
{ age: 21 }
// 结果:{ id: 1, name: 'Tom', age: 21, email: 'tom@example.com' }
OPTIONS 与 CORS 预检
浏览器在发送跨域的非简单请求前,会先发送 OPTIONS 预检请求:
// 跨域请求带自定义 header,会触发预检
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Custom-Header': 'value' // 自定义 header 触发预检
},
body: JSON.stringify({ data: 'test' })
})
// 浏览器会先发送:
// OPTIONS /data
// Access-Control-Request-Method: POST
// Access-Control-Request-Headers: content-type, x-custom-header
关键点
- GET 用于获取数据,POST 用于创建数据,两者最常用
- PUT 是完整替换,PATCH 是部分更新
- 幂等性:多次请求结果相同。GET、PUT、DELETE 幂等,POST、PATCH 不幂等
- OPTIONS 用于 CORS 预检,检查服务器是否允许跨域请求
- HEAD 与 GET 相同但不返回响应体,常用于检查资源是否存在或获取文件大小
目录