Ruby-on-rails POST json 到 rails 服务器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4914745/
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
POST json to rails server
提问by Rohan
def create
req = ActiveSupport::JSON.decode(request.body)
if user = User.authenticate(req["email"], req["password"])
session[:user_id] = user.id
render :json => "{\"r\": \"t\"}" + req
else
render :json => "{\"r\": \"f\"}"
end
end
'create' method is in a controller and mapped to "/login", I am setting correct content types and accept headers from my curl client. I am getting a 422 http status response all the time.
'create' 方法位于控制器中并映射到“/login”,我正在设置正确的内容类型并接受来自 curl 客户端的标头。我一直收到 422 http 状态响应。
Any suggestions?
有什么建议?
回答by Jesse Wolgamott
If you are sending in the right headers, then you won't need to do "ActiveSupport::JSON.decode" -- rails will do that for you.
如果您发送的是正确的标头,那么您将不需要执行“ActiveSupport::JSON.decode”——rails 会为您完成。
You'll need to set the following headers in your post.
您需要在帖子中设置以下标题。
Content-Type: application/json
Accept: application/json
A 422 means Unprocessable Entity --- generally that there was a validation failure.
422 表示不可处理实体——通常表示验证失败。
You should be able to have. If you can't, then your headers aren't set correctly.
你应该可以拥有。如果你不能,那么你的标题设置不正确。
def create
if user = User.authenticate(params["email"], params["password"])
session[:user_id] = user.id
render :json => "{\"r\": \"t\"}" + req
else
render :json => "{\"r\": \"f\"}"
end
end

