使用 REST 避免重复的 POST [英] Avoid duplicate POSTs with REST
问题描述
我一直在 REST API 中使用 POST 来创建对象.每隔一段时间,服务器就会创建对象,但客户端会在收到 201 Created
响应之前断开连接.客户端只看到失败的 POST 请求,稍后再试,服务器愉快地创建了一个重复的对象......
I have been using POST in a REST API to create objects. Every once in a while, the server will create the object, but the client will be disconnected before it receives the 201 Created
response. The client only sees a failed POST request, and tries again later, and the server happily creates a duplicate object...
其他人肯定也遇到过这个问题吧?但我在谷歌上搜索,似乎每个人都忽略了它.
Others must have had this problem, right? But I google around, and everyone just seems to ignore it.
我有两个解决方案:
A) 改用 PUT,并在客户端上创建 (GU)ID.
A) Use PUT instead, and create the (GU)ID on the client.
B) 为客户端上创建的所有对象添加一个 GUID,并让服务器强制执行它们的 UNIQUE
-ness.
B) Add a GUID to all objects created on the client, and have the server enforce their UNIQUE
-ness.
A 与现有框架不太匹配,而 B 感觉像是一个黑客.在现实世界中,其他人如何解决这个问题?
A doesn't match existing frameworks very well, and B feels like a hack. How does other people solve this, in the real world?
使用 Backbone.js,您可以在客户端上创建对象时将 GUID 设置为 id.当它被保存时,Backbone 会做一个 PUT 请求.让您的 REST 后端将 PUT 处理为不存在的 ID,然后您就设置好了.
With Backbone.js, you can set a GUID as the id when you create an object on the client. When it is saved, Backbone will do a PUT request. Make your REST backend handle PUT to non-existing id's, and you're set.
推荐答案
我总是使用 B -- 由于服务器端的任何问题而检测 dups.
I always use B -- detection of dups due to whatever problem belongs on the server side.
这篇关于使用 REST 避免重复的 POST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!