0

我想用json登录我的服务器。create 方法适用于我的自定义视图 (new.html.erb),但不适用于 json。我正在使用宝石设计。

会话控制器:

class SessionsController < ApplicationController

  respond_to :json

  def new
    #empty because no underlying model
  end


  def create
    user = User.find_by_email(params[:email])

    respond_to do |format|
      if user && user.authenticate(params[:password]) #because user has_secure_password
        session[:user_id] = user.id

        format.html { redirect_to images_path, notice: "Login successful!" }
        format.json { render :json => {:success => true,
                      :info => "Logged in" } }
      else
        format.html { flash.now.alert = "Wrong email or password"
                    render "new" }
        format.json { render :json => {:success => false, :info => "Wrong email or password" } }
      end
    end
  end



  def destroy

    session[:user_id] = nil
    respond_to do |format|
      format.html { redirect_to bookmarks_path, notice: "Logout successful!" }
      format.json { render :json => {:success => true,
                      :info => "Logged out",
                      :data => { } } }
    end

  end


end

用户.rb

    class User < ActiveRecord::Base

      attr_accessible :name, :email, :password, :password_confirmation, :remember_me, :encrypted_password

      has_secure_password

      validates :email, format: /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i, uniqueness: true

end

路线.rb:

#user
  resources :users , only: [:new, :create]

  #session
  get "login" => "sessions#new", as: "login"
  post "sessions" => "sessions#create", as: "sessions"
  delete "logout" => "sessions#destroy", as: "logout"

耙路线:

users POST   /users(.:format)           users#create
  new_user GET    /users/new(.:format)       users#new
     login GET    /login(.:format)           sessions#new
  sessions POST   /sessions(.:format)        sessions#create
    logout DELETE /logout(.:format)          sessions#destroy

我使用 Chrome 扩展 Simple REST Client 通过 HTTP POST 使用我的 json 数据测试服务器(用户已经存在于数据库中,并且可以从 new.html.erb 视图登录):

url:           http://localhost:3000/sessions
method:        POST
Content-Type:  application/json
               Accept: application/json
Data:          {"user":{ "email":"test@test.at","password":"asdf" }}

作为响应,我得到状态 200 OK,但是:

{"success":false,"info":"Wrong email or password"}

虽然电子邮件和密码是正确的。

4

1 回答 1

1

在 json 对象的根目录中提供电子邮件和密码,或者像params[:user][:email].

于 2013-06-23T15:58:32.137 回答