详细讲解HTTP请求方法:GET、POST、PUT、DELETE、PATCH、HEAD、OPTIONS等
从服务器获取指定资源,请求参数附加在URL中
GET /api/users?id=123向服务器提交数据,创建新资源,数据在请求体中
POST /api/users替换整个资源,需要提供完整资源数据
PUT /api/users/123局部更新资源,只发送需要修改的字段
PATCH /api/users/123删除指定的资源
DELETE /api/users/123只获取响应头,不返回响应体
HEAD /api/users/123用于代理服务器,建立隧道连接
CONNECT proxy.example.com:443用于诊断,回显服务器收到的请求
TRACE /api/users| 方法 | 安全性 | 幂等性 | 可缓存 | 请求体 | 响应体 |
|---|---|---|---|---|---|
| GET | ✓ 安全 | ✓ 幂等 | ✓ 是 | ✗ 否 | ✓ 是 |
| POST | ✗ 不安全 | ✗ 非幂等 | ✗ 否 | ✓ 是 | ✓ 是 |
| PUT | ✗ 不安全 | ✓ 幂等 | ✗ 否 | ✓ 是 | ✓ 是 |
| PATCH | ✗ 不安全 | ✗ 非幂等 | ✗ 否 | ✓ 是 | ✓ 是 |
| DELETE | ✗ 不安全 | ✓ 幂等 | ✗ 否 | ✗ 否 | ✓ 是 |
| HEAD | ✓ 安全 | ✓ 幂等 | ✓ 是 | ✗ 否 | ✗ 否 |
| ✓ 安全 | ✓ 幂等 | ✗ 否 | ✗ 否 | ✓ 是 |
// GET请求
fetch('https://api.example.com/users?id=123')
.then(response => response.json())
.then(data => console.log(data));
// POST请求
fetch('https://api.example.com/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: '张三', age: 25 })
})
.then(response => response.json())
.then(data => console.log(data));
// PUT请求
fetch('https://api.example.com/users/123', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: '张三', age: 26 })
})
.then(response => response.json())
.then(data => console.log(data));
// DELETE请求
fetch('https://api.example.com/users/123', {
method: 'DELETE'
})
.then(response => response.json())
.then(data => console.log(data));