HTTP 表单中 GET 方法的用途是什么

HTTP What is the purpose of GET method in forms

据我了解,GET 方法要求服务器向客户端的浏览器发送一些内容。我在 c# 中设置了一个 HTTPListener,当我访问 http://localhost:1330/form.html 时,我从客户端收到的请求是:GET /form.html,这意味着客户端在说“嘿服务器,我需要HTML 代码以在浏览器中显示该页面”,这是有道理的。如果我在 form.html 中设置 <form>method=POST,输入字段值位于 C# 中 context.Request.InputStream 中的请求正文中,看起来类似于:input_name1=value&input_name2=value2&input_name3=value3... 而 urL 仍然是 /form.html。这也是有道理的,客户端时代:“嘿服务器,获取写入 HTML <input> 元素的数据”,服务器使用它,可能将其存储在数据库中或计算一些东西并发送它返回给客户端。现在,如果我将表单方法设置为 GET,URL 将修改为:/form.html?input_name1=value&input_name2=value2&input_name3=value3 并且 context.Request.InputStream 保持空白,这与 POST 相反,其中 InputStream包含数据并且 URL 没有查询。对我来说,表单中的 GET 方法毫无意义。为什么我们需要从表单客户端获取数据,将其发送到服务器,然后将其原封不动地返回给客户端。为什么我要从浏览器将数据发送到 C#,然后将其发送回浏览器,如果我可以使用简单的 javascript 在客户端获取它?在浏览器向服务器发出带有查询的 GET 请求的那一刻,客户端浏览器已经拥有该数据,那么如果它已经在客户端浏览器中,为什么还要要求服务器提供它呢?

一般来说,HTTP GET 方法用于从服务器接收数据,而 HTTP POST 用于修改数据或向资源添加数据。

例如,考虑一个搜索表单。表单上可能有一些字段用于筛选结果,例如SearchTermStart/EndDateCategoryLocationIsActive等。您从服务器请求结果,但不修改任何数据。这些字段将由客户端添加到 GET 请求中,以便服务器可以过滤并 return 您请求的结果。

来自 MDN 文章 Sending form data:

Each time you want to reach a resource on the Web, the browser sends a request to a URL. An HTTP request consists of two parts: a header that contains a set of global metadata about the browser's capabilities, and a body that can contain information necessary for the server to process the specific request.

GET 请求没有请求主体,因此参数被添加到 URL(如果您有兴趣,这在 HTTP spec 中定义)。

The GET method is the method used by the browser to ask the server to send back a given resource: "Hey server, I want to get this resource." In this case, the browser sends an empty body. Because the body is empty, if a form is sent using this method the data sent to the server is appended to the URL.

HTTP POST 方法使用请求正文添加参数。通常在 POST 中,您将添加资源或修改现有资源。

The POST method is a little different. It's the method the browser uses to talk to the server when asking for a response that takes into account the data provided in the body of the HTTP request: "Hey server, take a look at this data and send me back an appropriate result." If a form is sent using this method, the data is appended to the body of the HTTP request.

网上有很多资源可以了解 HTTP 协议和 HTTP verbs/methods。 MDN 文章HTTP 概述Sending form dataHTTP 请求方法 应该提供一些很好的介绍性读物material。