HTTP 之 请求方法(三)

1. GET:请求指定的资源。

GET 请求应该只用于获取数据,而不会导致服务器上的状态变化。

//通常用于请求页面或数据。
fetch('http://www.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

2. POST:向服务器提交新的资源。

POST 请求通常用于表单提交或上传文件,数据在请求体中。

//提交用户注册信息。
fetch('http://www.example.com/register', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    username: 'newuser',
    password: 'newpass'
  })
})
.then(response => response.json())
.then(data => console.log('Registered:', data))
.catch(error => console.error('Error:', error));

3. PUT:更新服务器上的现有资源。

如果资源不存在,则可能会创建新资源。PUT 请求是幂等的。

//更新用户的配置信息。
fetch('http://www.example.com/settings', {
  method: 'PUT',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    theme: 'dark',
    notifications: true
  })
})
.then(response => response.json())
.then(data => console.log('Settings Updated:', data))
.catch(error => console.error('Error:', error));

4. DELETE:从服务器删除指定的资源。

DELETE 请求通常用于删除资源。

//删除用户的账户。
fetch('http://www.example.com/users/123', {
  method: 'DELETE'
})
.then(response => response.json())
.then(data => console.log('Delete Response:', data))
.catch(error => console.error('Error:', error));

5. HEAD:请求资源的响应头信息,不返回响应体。

HEAD 请求与 GET 类似,但不包括响应体。

//检查资源是否存在或获取资源的元数据。
fetch('http://www.example.com/image.png', {
  method: 'HEAD'
})
.then(response => {
  console.log(`Content-Type: ${response.headers.get('Content-Type')}`);
})
.catch(error => console.error('Error:', error));

6. OPTIONS:描述目标资源的通信选项。

OPTIONS 请求通常用于跨域资源共享(CORS)的预检请求。

//获取服务器支持的 HTTP 方法。
fetch('http://www.example.com/api/resource', {
  method: 'OPTIONS'
})
.then(response => response.json())
.then(data => console.log('Allowed Methods:', data))
.catch(error => console.error('Error:', error));

7. TRACE:沿着到目标资源的路径执行一个消息环回测试。

TRACE 请求通常用于诊断。
fetch('http://www.example.com/trace', {
  method: 'TRACE'
})
.then(response => response.text())
.then(data => console.log('Trace Response:', data))
.catch(error => console.error('Error:', error));

8. CONNECT:建立一个到服务器的隧道,通常用于 SSL 加密的代理请求。

不常用于前端开发中,主要用于通过代理服务器建立安全连接。
通常不会在前端代码中看到 CONNECT 方法的使用。

9. PATCH:对资源进行部分更新。

PATCH 请求允许只发送需要更新的部分数据。

fetch('http://www.example.com/users/123', {
  method: 'PATCH',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    email: 'newemail@example.com'
  })
})
.then(response => response.json())
.then(data => console.log('User Updated:', data))
.catch(error => console.error('Error:', error));
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

**之火

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值