GET和POST的区别

get VS post
相信小伙伴在面试中常常遇到面试官问道 GET 和 POST 两种请求方式有什么区别,

相信大家马上就能想到

GET 请求可被缓存

GET 请求保留在浏览器历史记录中

GET 请求可被收藏为书签

GET 请求不应在处理敏感数据时使用

GET 请求有长度限制

GET 请求只应当用于取回数据(不修改)

POST 请求不会被缓存

POST 请求不会保留在浏览器历史记录中

POST 不能被收藏为书签

POST 请求对数据长度没要求

轻轻松松答出了一个满意的答案 (以上答案参考 w3school)

GET

  • 请求是否有主体 否
  • 成功的响应是否有主体 是
  • 安全 是
  • 幂等 是
  • 可缓存 是
  • HTML 表单是否支持 是

POST

  • 请求是否有主体 是
  • 成功的响应是否有主体 是
  • 安全 否
  • 幂等 否
  • 可缓存 Only if freshness information is - included
  • HTML 表单是否支持 是

关于有人说 GET 不安全会暴露参数数据而 POST 安全等

通过查阅http文档中定义的安全方法得知 GET 方法被定义为安全方法

Safe Methods

Request methods are considered “safe” if their defined semantics are
essentially read-only; i.e., the client does not request, and does
not expect, any state change on the origin server as a result of
applying a safe method to a target resource. Likewise, reasonable
use of a safe method is not expected to cause any harm, loss of
property, or unusual burden on the origin server.

This definition of safe methods does not prevent an implementation
from including behavior that is potentially harmful, that is not
entirely read-only, or that causes side effects while invoking a safe
method. What is important, however, is that the client did not
request that additional behavior and cannot be held accountable for
it. For example, most servers append request information to access
log files at the completion of every response, regardless of the
method, and that is considered safe even though the log storage might
become full and crash the server. Likewise, a safe request initiated
by selecting an advertisement on the Web will often have the side
effect of charging an advertising account.

Of the request methods defined by this specification, the GET, HEAD,
OPTIONS, and TRACE methods are defined to be safe.

这里的安全是对服务器数据来说的,你通过 GET 方法获取数据,无法对数据做出破坏行为,而 POST 则不会。但有时我们所表达的 GET 不安全其实说的是 GET 的幂等 以及可留下浏览记录

get <=> json <=> post
例:

银行网站 A,它以 GET 请求来完成银行转账的操作,如:https://www.xxx.com/Transfer.php?toBankId=11&money=1000
危险网站 B,它里面有一段 HTML 的代码如下:

1
< img src=https://www.xxx.com/Transfer.php?toBankId=11&money=1000/>

首先,你登录了银行网站 A,然后访问危险网站 B,噢,这时你会发现你的银行账户少了 1000 块……

例:

登录某网站 https://xxx.com/login?user=admin&password=admin
当别人浏览你的历史记录时就可以知道你的账号密码

-------------本文结束感谢您的阅读-------------
坚持原创技术分享,您的支持将鼓励我继续创作!
0%