我已经开始为rails应用程序创建Api。我当前正在创建用于登录的会话控制器。
但由于某种原因,我得到了这个错误
NoMethodError
in Api::V1::SessionsController#create
undefined method `downcase' for nil:NilClass;
我不明白为什么会发生这种事。我还在我的传统会话控制器中使用下变频方法,我没有这个问题。
API控制器
module Api
module V1
class SessionsController < ApplicationController
skip_before_filter :verify_authenticity_token,
:if => Proc.new { |c| c.request.format == 'application/json' }
respond_to :json
def create
user = User.find_by_email(params[:session][:email].downcase)
if user && user.authenticate(params[:session][:password])
sign_in user
end
render :status => 200,
:json => { :success => true,
:info => "Logged In Successfully",
:data => { } }
end
end
end
end
控制器
class SessionsController < ApplicationController
def create
user = User.find_by_email(params[:session][:email].downcase) ###THIS WORKS FINE
if user && user.authenticate(params[:session][:password])
sign_in user
redirect_to publishers_path
end
end
end
路线
# API Routes
namespace :api, defaults: {format: 'json'} do
scope module: :v1, constraints: ApiConstraints.new(version: 1, default: true) do
resources :sessions, only: [:new, :create, :destroy]
end
end
问题是您检查params[:session][:email]
但使用卷曲调用:
curl -v -H 'Content-Type: application/json' -H 'Accept: application/json' -X POST localhost:3000/api/sessions -d "{"user":{"email":"secret@gmail.com","password":"secret"}}"
电子邮件仍将存储在params[:user][:email]
中
此外,您应该检查用户是否将该参数传递给了您的are api,因为您已经注意到,如果没有它,它将失败
user = User.find_by_email(params[:user][:email].downcase) if defined? params[:user][:email]