Rails 6.0.0 TypeError-没有将nil隐式转换为String:

时间:2019-11-19 15:48:26

标签: ruby-on-rails api authentication

人们,所以在尝试进行后期API调用时遇到了这个问题。 情况是这样的: 我有一个大型应用程序,学生可以在其中注册,这样我可以管理他们并通过该学生管理应用程序与他们联系。 现在,我创建了一个较小的应用程序,学生可以在该应用程序中进行作业,可以调用该作业。 我正在登录部分中对更大的应用程序进行后期API调用,因此学生不必再次注册,他们可以在两个应用程序中使用相同的信息。 我收到内部服务器错误500;在终端中的错误是:

TypeError - no implicit conversion of nil into String:
 app/controllers/api/sessions_controller.rb:12:in `create'

这是学生管理应用中的会话控制器中的创建操作:

  def create
    unless request.format == :json
      sign_out
      render status: 406, json: { message: "JSON requests only." } and return
    end
    resource = warden.authenticate!(auth_options)

    if resource.blank?
      render status: 401, json: { response: "Access denied." } and return
    end

    sign_in(resource_name, resource)
    respond_with resource, location:
    after_sign_in_path_for(resource) do |format|
      format.json { render json:
        {
          success: true, jwt: current_token, response: "Authentication successful"
        }
      }
    end

  end

,最重要的是使用非常简单的html形式的api调用: ps:我在本地运行项目,这就是为什么将URL定义为localhost

<form class="login-form">
  <input type="email" class="mail mail-input" placeholder=" Email"><br>
  <input type="password" class="password pw-input" placeholder=" Password"><br>
  <button class="login" type="button" name="button">Login</button>
</form>

<script>

var login = document.querySelector(".login")
login.addEventListener("click", function(){
  var email = document.querySelector(".mail")
  var password = document.querySelector(".password")
  let loginValues = {
    email: email.value,
    password: password.value
  }
  $.post (
   "http://localhost:4000/api/login.json",
    {
      api_user: {
        email: email.value,
        password: password.value
      }
    },
    function (response){
      console.log(response)
      console.log('in');
      window.location.replace("http://localhost:3000/")
    }
  )
})

</script>

1 个答案:

答案 0 :(得分:0)

您可以尝试替换它吗?

api_user: {
  email: email.value,
  password: password.value
}

与此:

user: {
  email: email.value,
  password: password.value
}

告诉我是否可行?

更新,基于评论:

我真的不知道您在上面的代码中正在做什么,代码真的很杂乱。尝试替换此代码:

respond_with resource, location:
after_sign_in_path_for(resource) do |format|
  format.json { render json:
    {
      success: true, jwt: current_token, response: "Authentication successful"
    }
  }
end

与此:

respond_with resource do |format|
  format.json { render json:
    {
      success: true, jwt: current_token, response: "Authentication successful"
    }
  }
end