【问题标题】:Restful api with rails带有 Rails 的 Restful api
【发布时间】:2017-03-07 07:20:16
【问题描述】:

我正在学习如何使用 RoR 编写一个宁静的 API,并有一个与之相关的问题。所以,我将解释我在代码中做了什么。

这是我的控制器的样子:

class EmployeesController < ApplicationController
  require 'rest_client'

  def index
    uri           = "localhost:3000/employees"
    rest_resource = RestClient::Resource.new(uri)
    users         = rest_resource.get # will get back you all the detail in json format, but it will we wraped as string, so we will parse it in the next step.
    @users = JSON.parse(users, :symbolize_names => true) # convert the return data into array
    @users.each do |u|
      logger.info(u.id)
    end
    # return based on the format type
    respond_to do |format|
      format.json {render json: @users}
      format.xml  {render xml:  @users}
      format.html
    end
  end

结束

在我的 Gemfile 中,我也包含了 rest-client。

gem 'rest-client'

我的路线是: 根'员工#index' 资源“员工”

希望到目前为止一切都好。

现在,当我发送时:

-> curl请求到'http://localhost:3000/employees',卡住了。

-> 获取请求(通过在浏览器中输入)'http://localhost:3000/',它也卡在这里。

我错过了什么?

【问题讨论】:

  • /employess 是否命中了EmployeesController#index?
  • @Santhosh,是的,它成功了。
  • 这不是无限循环吗?
  • @Santhosh,为什么?
  • 你的目标是返回 Json 吗?

标签: ruby-on-rails ruby rest


【解决方案1】:

您不需要 RestClient,因为您在这里编写的是服务器,而不是客户端。浏览器充当客户端。在创建循环时删除对 localhost 的调用。

这个 URL 应该已经在你的 routes.rb 中设置好了,可能使用:

 resources :users

假设这是一个典型的应用程序,show 函数应该使用 ActiveRecord 从数据库中读取。

class EmployeesController < ApplicationController
  def index
    @users = User.all
    respond_to do |format|
      format.json {render json: @users}
      format.xml  {render xml:  @users}
      format.html
    end
  end
end

【讨论】:

  • 我也在尝试“卷曲”,我想我需要一个休息客户端。有意义吗?
  • @mahemoff,我不明白。为什么我将“用户”声明为资源?
  • 如果您尝试创建从数据库读取用户的标准服务,则无需 curl。服务器从数据库中获取数据,而不是其他服务。然后,您可以通过将浏览器指向 localhost:3000 来测试它
  • 如果不确定资源,我会读这篇文章 - guides.rubyonrails.org/routing.html。这是在 Rails 中设置 URL 的关键部分。
  • 另外,我使用 curl 作为客户端,而不是浏览器。所以,我写这篇文章是为了在控制台线上获得 Json 响应。 curl 'localhost:3000/employees'
【解决方案2】:

您是否在 localhost:3000 上运行了其他应用程序?因为如果不是,那么您的服务器所做的就是一次又一次地调用自己,从而导致循环。

如果您确实有其他一些应用程序从数据库中获取用户,那么请确保它在其他端口上运行,而不是您的 rails 应用程序。

如果你只有 1 个应用,那么你不需要 rest 客户端。

【讨论】:

    【解决方案3】:

    实际上,您无需任何额外的宝石就可以做到这一点。您只需要根据要向 API 用户公开的内容声明路由并相应地返回类型(xml、json、...)。

    【讨论】:

      猜你喜欢
      • 2018-03-08
      • 2015-03-07
      • 2023-02-10
      • 1970-01-01
      • 2013-07-27
      • 2013-09-25
      • 1970-01-01
      • 1970-01-01
      • 2011-07-17
      相关资源
      最近更新 更多