【发布时间】:2017-12-28 18:41:49
【问题描述】:
我编写了一个 Rails API 后端。通过在终端中查看我的服务器,我可以看到端点正在受到攻击。我还可以在 Postman 中看到返回。但是,我无法在我的 React 前端返回有效负载。这是我在 React 中的 fetch 调用(我有调试器,但它们没有被命中):
handleSearch(video) {
fetch(`http://localhost:3000/api/v1/search?q=${video}`)
.then((response) => {
debugger
return response.json()
})
.then((data) => {
debugger
})
}
这是我的 api 控制器:
def index
videos = VideoService.search_content(params['q'])
render json: videos
end
这是我在终端服务器中的输出:
Started GET "/api/v1/search?q=Firefly" for 127.0.0.1 at 2017-12-28 11:40:38 -0700
Processing by Api::V1::SearchController#index as */*
Parameters: {"q"=>"Firefly"}
Completed 200 OK in 426ms (Views: 7.5ms | ActiveRecord: 0.0ms)
我不太确定问题出在哪里。在发出 api 请求时,我从来没有遇到过问题。就像我说的。我可以看到正在与之交互的服务器,并且可以在 Postman 中看到有效负载返回。感谢您的帮助!
编辑: 以下是我在下降过程中调用 handleSearch 的方式:
<SideBar
info={this.state.info}
logout={this.handleLogout.bind(this)}
search={this.handleSearch.bind(this)}
/>
这里是在SideBar 组件中调用的:
searchHandler(video) {
this.props.search(video)
}
<SearchBox search={this.searchHandler.bind(this)}/>
最后是输入的实际来源:
handleSearch(e){
let video = e.target.previousSibling.value
this.props.search(video)
}
render() {
return(
<form className="search-box" >
<input type="text" placeholder="Search.." name="search"/>
<button className="fa fa-search" type="submit" onClick={this.handleSearch.bind(this)}>
</button>
</form>
)
}
【问题讨论】:
-
您是否在控制台中看到任何错误?如果您使用 Postman 获取有效负载并且您的控制器操作返回 200,则错误似乎来自您的 JavaScript 某处。在我看来,其他一切都很好。
-
你是怎么调用handleSearch方法的?
-
我将props中的handleSearch传递给另一个组件中的按钮/输入字段,然后将搜索词返回给这个函数。 @PatrickHund
-
尝试在获取结果中添加一个 catch 方法调用,看看调试器是否命中
-
@DerekHopper 不,仍然没有命中。我在那里兴奋了一秒钟,:P
标签: javascript ruby-on-rails ruby reactjs api