这真的让我挠头了。我想做的应该是非常直截了当,但由于某些原因,我只是无法使它发挥作用。
正如标题所述,我正在尝试从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。我的假设是,我可以取得一个相同的点,但我想我错过了什么。
有几件事要注意
formulas的状态,结果是相同的。(例如:formulas: body.formulas、formulas: body.coffee_formulas等)NoMethodError (undefined method 'coffee_formulas' for nil:NilClass):
500 (Internal Server Error)就像我说的,我认为这是一件非常简单的事情,但我想我错过了一个非常关键的细节。任何建议都将不胜感激!
发布于 2017-11-08 00:28:53
因此,它最终成为了一个问题的获取它自己。控制器实际上是在做我希望它做的事情,但是提取需要格式化如下:
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
})
})
} 发布于 2017-11-05 17:48:49
NoMethodError (undefined method 'coffee_formulas' for nil:NilClass)意味着您试图在nil类上调用coffe_formulas方法。您的current_user助手返回nil,因此您还没有授权您的请求。
https://stackoverflow.com/questions/47124577
复制相似问题