尝试从 React 前端获取 Rails API 端点时出现 NoMethodError

NoMethodError when trying to fetch to Rails API endpoint from React frontend

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

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

我的抓取看起来像这样:

  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。我的假设是我可以获取相同的点,但我想我遗漏了一些东西。

一些注意事项

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

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

NoMethodError (undefined method 'coffee_formulas' for nil:NilClass) 表示您正在尝试在 nil class 上调用 coffe_formulas 方法。你的 current_user 助手 returns nil 所以你还没有授权你的请求。

所以它最终成为获取自身的问题。控制器实际上正在做我想做的事情,但提取需要格式化为:

  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
      })
    })
  }