简体   繁体   English

什么时候使用 get vs post 请求合适

[英]when is it appropriate to use get vs post request

Background背景

Let's assume i have some data as follows that i collect based on some survey users fill out in a form:让我们假设我有一些数据如下,这些数据是我根据一些调查用户填写的表格收集的:

{
  "brand": "Nike",
  "size": [
    "small",
    "medium"
  ]
}

Now let's say I want to pass this data to some api , in my case i will create api gateway that will forward this request to a aws lambda function.现在假设我想将此数据传递给某个 api ,在我的情况下,我将创建 api 网关,将这个请求转发到 aws lambda 函数。 The lambda function request will process this request and look at my rds instance to get all the shirts that are small and medium and return me data as response. lambda 函数请求将处理此请求并查看我的 rds 实例以获取所有中小型衬衫并将数据作为响应返回给我。

My question:我的问题:

When I make the ajax call to the api would this be a get request or a post request??当我对 api 进行 ajax 调用时,这是获取请求还是发布请求?

Technically I am not really going to modify the database but rather do a read on the database something like select * from nike where size = 'small' and size = 'medium'从技术上讲,我并不是真的要修改数据库,而是读取数据库,例如select * from nike where size = 'small' and size = 'medium'

I am confused because i assumed whenever we are trying to "GET"/read some data we do a GET request.我很困惑,因为我假设每当我们尝试“获取”/读取一些数据时,我们都会执行 GET 请求。 However I came across THIS stackoverflow post.但是我遇到了这个stackoverflow 帖子。 where the accepted answer suggests that when we are passing data long like i am above we should rather make a POST request.接受的答案表明,当我们像上面那样长时间传递数据时,我们应该发出 POST 请求。

So my ajax call would look something like this possibly:所以我的 ajax 调用可能看起来像这样:

var data =  {
      "brand": "Nike",
      "size": [
        "small",
        "medium"
      ]
    }


$.ajax({
  type: "POST",
  url: "apigatewayendpointblahblah",
  data: data,
  success: success,
  dataType: dataType
});

The Rest Protocol has strict definitions for the methods you should use. Rest 协议对您应该使用的方法有严格的定义。 when you're fetching data without modifying it, you should use GET request.当您在不修改数据的情况下获取数据时,您应该使用 GET 请求。

Notice that GET required query params rather than body params, which then can be used as a link for sharing pages.请注意,GET 需要查询参数而不是正文参数,然后可以将其用作共享页面的链接。

Refer to https://restfulapi.net/http-methods/ for more info有关更多信息,请参阅https://restfulapi.net/http-methods/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM