HTTP协议中的PUT、POST和PATCH方法有什么区别?


当前回答

下面的定义来自真实世界的例子。

示例概述 对于每个客户端数据,我们存储一个标识符来查找客户端数据,并将该标识符发送回客户端以供参考。

POST If the client sends data without any identifier, then we will store the data and assign/generate a new identifier. If the client again sends the same data without any identifier, then we will store the data and assign/generate a new identifier. Note: Duplication is allowed here. PUT If the client sends data with an identifier, then we will check whether that identifier exists. If the identifier exists, we will update the resource with the data, else we will create a resource with the data and assign/generate a new identifier. PATCH If the client sends data with an identifier, then we will check whether that identifier exists. If the identifier exists, we will update the resource with the data, else we will throw an exception.

注意:在PUT方法中,如果没有找到标识符,我们不会抛出异常。但是在PATCH方法中,如果没有找到标识符,则抛出异常。

如果您对上述内容有任何疑问,请告诉我。

其他回答

PUT =用所提供的新表示替换整个RESOURCE

PATCH =用所提供的值替换源资源的部分和|或资源的其他部分被更新,你没有提供(时间戳)和|或更新资源影响其他资源(关系)

https://laracasts.com/discuss/channels/general-discussion/whats-the-differences-between-put-and-patch?page=1

这样想吧……

POST - create

PUT -替换

补丁-更新

GET - read

DELETE -删除

PUT和PATCH请求的主要区别:

假设我们有一个资源,其中包含一个人的姓和名。

如果我们想要改变名字,那么我们发送一个put请求Update

{"第一个":"迈克尔","最后一个":"安吉洛"}

在这里,虽然我们只改变了名字,但是对于PUT请求,我们必须在第一个和最后一个发送参数。 换句话说,必须再次发送所有值,即完整的有效负载。

然而,当我们发送PATCH请求时,我们只发送我们想要更新的数据。换句话说,我们只发送名字来更新,不需要发送姓氏。

这里是一个简单的描述:

POST总是用于创建资源(是否复制并不重要) PUT用于检查资源是否存在,然后更新,否则创建新的资源 PATCH总是用于更新资源

你可能会把restful HTTP方法理解为javascript中对数组的相应操作(索引偏移量为1)。

请看下面的例子:

Method Url Meaning
GET /users return users array
GET /users/1 return users[1] object
POST /users users.push(body); return last id or index
PUT /users replace users array
PUT /users/1 users[1] = body
PATCH /users/1 users[1] = {...users[1], ...body }
DELETE /users/1 delete users[1]