【问题标题】:NoMethodError when trying to fetch to Rails API endpoint from React frontend尝试从 React 前端获取 Rails API 端点时出现 NoMethodError
【发布时间】:2017-11-05 17:40:52
【问题描述】:

这真的让我摸不着头脑。我正在尝试做的事情应该很简单,但由于某种原因我无法让它发挥作用。

正如标题所说,我正在尝试从我设置为在 React 组件中显示的 Rails API 端点获取一些信息。

我的抓取看起来像这样:

  componentDidMount() {
    fetch(`/api/v1/coffee_formulas`)
    .then(response => response.json())
    .then(body => {
      this.setState({ formulas: body })
    })
  }

API 端点如下所示:

  def index
    formulas = current_user.coffee_formulas
    render json: { status: 'SUCCESS', message: 'Loaded coffee formulas', coffee_formulas: formulas }, status: :ok
  end

让我感到困惑的是,我可以导航到 http://localhost:3000/api/v1/coffee_formulas 并查看我想要在 React 端获取的确切 JSON。我的假设是我可以提取到同一点,但我想我错过了一些东西。

注意事项

  • 我能够成功发布到同一个 API。
  • 我正在使用 Google OmniAuth 生成会话和 current_user。
  • 我尝试了几种不同的方式设置formulas 的状态,结果相同。 (例如:formulas: body.formulasformulas: body.coffee_formulas 等)
  • 我在终端中看到的确切错误是:

NoMethodError (undefined method 'coffee_formulas' for nil:NilClass):

  • 我的控制台中的错误是500 (Internal Server Error)

就像我说的那样,我认为这是一件非常简单的事情,但我想我在这里遗漏了一个非常关键的细节。任何建议将不胜感激!

【问题讨论】:

    标签: ruby-on-rails reactjs google-oauth fetch


    【解决方案1】:

    所以它最终成为 fetch 自身的问题。控制器实际上正在执行我想要的操作,但是需要将 fetch 格式化为:

      componentDidMount() {
      fetch(`/api/v1/coffee_formulas.json`, {
        credentials: 'same-origin',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        method: 'GET'
      }).then(response => response.json())
        .then(body => {
          this.setState({
            formulas: body.coffee_formulas,
            user: body.current_user
          })
        })
      } 
    

    【讨论】:

      【解决方案2】:

      NoMethodError (undefined method 'coffee_formulas' for nil:NilClass) 表示您正在尝试在 nil 类上调用 coffe_formulas 方法。您的 current_user 助手返回 nil,因此您尚未授权您的请求。

      【讨论】:

      • 我想我仍然不清楚我没有得到什么。如果我只是通过将formulas = current_user.coffee_formulas 更改为formulas = CoffeeFormula.all 来获取数据库中的所有coffee_formulas,我的终端不会出现错误,但是当我尝试查看formulas 的状态时,我仍然一无所获。让我感到困惑的另一件事是 current_user 如何以 nil 的形式返回,但是当我转到 http://localhost:3000/api/v1/coffee_formulas 时,我只看到与 current_user 相关的信息。切换帐户更新也应如此。
      • index 方法签名之后添加一个断点,例如 pry 并查看当通过 react 调用时您为 current_user 得到什么
      • @awesome_treehouse 您可能正在使用devise gem。您确定已在控制器中添加了以下行吗? before_action :authenticate_user! 没有这个回调 current_user 将不会被解析。
      • @Gregy,所以我实际上并没有使用设计。只是gem 'omniauth-google-oauth2'。在我的 ApplicationController 中,我有一个帮助方法,它定义了 current_user,我认为它可以让我访问已登录的用户。
      • @awesome_treehouse 你能用你的current_user 方法更新问题吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多