Ruby-on-rails 为什么 Rails 要为 JSON PUT 请求返回“head :no_content”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14716151/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why does Rails want to return "head :no_content" for JSON PUT requests?
提问by goggin13
After I runrails generate scaffold User
The generated controller function in Rails 3.2.11 for updating a user looks like this:
在运行rails generate scaffold User
Rails 3.2.11 中生成的用于更新用户的控制器函数后,如下所示:
def update
@user = User.find(params[:id])
respond_to do |format|
if @user.update_attributes(params[:user])
format.html { redirect_to @user, notice: 'User was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
The line I'm curious about is returning head :no_contentfor a successful JSON update request. I've done some googling, as I was guessing that this is some sort of RESTful property, to not return the updated object, but I couldn't find anything that claimed that was the case.
我很好奇的行是返回head :no_content成功的 JSON 更新请求。我做了一些谷歌搜索,因为我猜测这是某种 RESTful 属性,不返回更新的对象,但我找不到任何声称是这种情况的东西。
Why is this the default, versus returning the JSON representation of the User object post-update?
为什么这是默认设置,而不是在更新后返回 User 对象的 JSON 表示?
采纳答案by 0x4a6f4672
Good question, apparently the purpose is to return a HTTP status code 200 with an empty body, see this discussion. Maybe for brevity or security purposes. head :no_contentseems to create a HTTP response 200 (success) with an empty body, returning this response header:
好问题,显然目的是返回带有空体的 HTTP 状态代码 200,请参阅此讨论。也许是为了简洁或安全目的。head :no_content似乎创建了一个空正文的 HTTP 响应 200(成功),返回此响应标头:
Status Code:200 OK
see also this related question.
另请参阅此相关问题。

