POST json到rails服务器

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’方法在控制器中并映射到“/ login”,我正在设置正确的内容类型并从我的curl客户端接受标头。 我一直收到422 http状态响应。

有什么建议?

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

您需要在post中设置以下标题。

 Content-Type: application/json Accept: application/json 

A 422表示不可处理的实体 – 通常是validation失败。

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

 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