【发布时间】:2018-08-31 07:57:42
【问题描述】:
我正在开发作为 API 的 Rails 5.0.6。我还在节点服务器版本 v9.8.0 上运行前端的 React 应用程序。在 localhost:3000 上运行的 React 应用程序上,我收到以下错误:
rails 用作 API,因此在控制器中我以 json 格式返回 @drinks。
drinks_controller.rb
class DrinksController < ApiController
# GET /drinks
def index
@drinks = Drink.select("id,title").all
render json: @drinks.to_json
end
# GET /drinks/1
def show
@drink = Drink.find(params[:id])
render json: @drink.to_json(:include => { :ingredients => { :only => [:id, :description] }})
end
end
我在Profile.dev 中使用Procfile 在本地运行两台服务器
web: cd client && PORT=3000 npm start
api: PORT=3001 && bundle exec rails s
当我访问在 localhost:3001/api/drinks 上运行的 rails 服务器时,我得到以下信息:
[{"id":1,"title":"Sparkling Negroni"},{"id":2,"title":"Pineapple-Jalapeño Margarita"}]
它是 json 格式,在 app.js 上我从那个端点获取
class App extends Component {
componentDidMount() {
window.fetch('api/drinks')
.then(response => response.json())
.then(json => console.log(json))
.catch(error => console.log(error))
}
代理不工作吗?
{
"name": "package-json",
"version": "4.0.1",
"description": "Get metadata of a package from the npm registry",
"license": "MIT",
"repository": "sindresorhus/package-json",
"proxy": "http://localhost:3001",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
}
我不明白问题是什么?
【问题讨论】:
-
我看到您正在使用开发人员工具栏,您的网络面板中发生了什么?您的服务器返回什么响应?
-
@JoseJimenez 我用网络图片更新了帖子
-
为了确定,试试
window.fetch('/api/drinks') -
@StevenAguilar 您可以单击网络面板中的 /api/drinks 行,然后在结果屏幕中查找“响应”或“预览”选项卡。它应该向您显示从您的 Rails 应用程序返回的内容。
标签: ruby-on-rails reactjs proxy rails-api procfile