get 和 post请求区别

90 阅读1分钟

1. 使用场景

  • get 更适合获取资源数据
    • 获取数据、搜索、过滤(参数简单且非敏感)
  • post 更适合对资源进行增删改的操作
    • 提交表单、敏感数据(如登录)、上传文件或需复杂编码的场景。

2. 参数传递

  • get 是明文放在url后面字符串拼接,敏感信息需要注意
  • post 是放在body

3. 参数长度

  • get 参数长度限制,但根据不同浏览器表现不一样,一般2048个字符
  • post 理论上没有限制,但是需要根据服务器有不同要求

4. 幂等性

  • get 是等性,多次请求,不会改变资源状态,更适合获取资源
  • post 是非幂等性,多次请求,每次请求会创建新资源

5. 安全性

  • get url明文传输,安全性更差
  • post 放在body中相对来说要好点

6. 浏览器缓存

  • get 会被浏览器缓存,页面刷新/回退无副作用
  • post 不会缓存,刷新页面可能会重复提交

7. 编码类型

  • get 仅支持 application/x-www-form-urlencoded 编码(URL编码)。
  • post 支持多种(如 multipart/form-data, applicetion/json),适合复杂数据传输(文件/表单)

示例:

GET请求(使用fetch

fetch('https://api.example.com/data?userId=123')
  .then(response => response.json())
  .then(data => console.log(data));

POST请求(使用fetch

fetch('https://api.example.com/submit', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ username: 'John', password: '123' })
})
.then(response => response.json())
.then(data => console.log(data));