POST json到rails服务器

Roh*_*han 25 ruby post json ruby-on-rails http

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
Run Code Online (Sandbox Code Playgroud)

'create'方法在控制器中并映射到"/ login",我正在设置正确的内容类型并从我的curl客户端接受标题.我一直收到422 http状态响应.

有什么建议?

Jes*_*ott 45

如果您要发送正确的标题,那么您将不需要执行"ActiveSupport :: JSON.decode" - rails将为您执行此操作.

您需要在帖子中设置以下标题.

Content-Type: application/json
Accept: application/json
Run Code Online (Sandbox Code Playgroud)

422表示不可处理的实体 - 通常是验证失败.

你应该能够拥有.如果你不能,那么你的标题设置不正确.

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
Run Code Online (Sandbox Code Playgroud)

  • 顺便说一下,如果你将请求头发送到服务器,请确保使用:而不是=,如:"Content-Type:application/json"和"Accepts:application/json" (4认同)