我有一个spa(单页应用程序),所以它广泛使用ajax来获取和保存服务器之间的数据。在一种情况下,我允许管理员查看/添加/编辑/删除用户。此区域的某些当前URL如下所示:
(GET) /users?userId=1 // get user with id of 1
(POST) /users?userId=1&firstName=Jim // update the first name of the user with id 1
(POST) /users?firstName=Bob // create a new use with the first name Bob
(POST) /users?userId=1&delete=true // delete user with id of 1
在相关项目中花了一些时间研究restful api之后,我想知道在web应用程序中是否更喜欢使用http类型(get、post、put、delete)。另外,使用用户id的路径参数而不是查询参数是否更好?从长远来看,这些url(重写上面的url)是一个更好的选择吗?
(GET) /users/1 // get user with id of 1
(PUT) /users/1?firstName=Jim // update the first name of the user with id 1
(POST) /users?firstName=Bob // create a new use with the first name Bob
(DELETE) /users/1 // delete user with id of 1
最佳答案
理论上是的,你应该。您应该尽可能地使用restful,这意味着要充分使用http语义。然而,现实是有点模糊,几个旧的浏览器,我不需要命名,不支持任何东西,除了GET
和POST
。因此,当前的建议是,在这些浏览器停止支持之前,或者在您放弃对这些浏览器的支持之前,使用备份方法来执行相同的操作,但在POST
上,通常在url中使用一个额外的参数或段。