我正在学习如何使用RoR编写一个restful 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'
我的路线是: root'员工#index' 资源'员工'
希望到现在为止一切都很好。
现在,当我发送:
- &GT;卷曲请求“http://localhost:3000/employees”,它会卡住。
- &GT;获取请求(通过在浏览器中输入)到“http://localhost:3000/”,它也会被卡在这里。
我缺少的是什么?
答案 0 :(得分:1)
您在此处编写服务器时不需要RestClient,而不是客户端。浏览器充当客户端。删除对localhost的调用,因为它正在创建一个循环。
此URL的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
答案 1 :(得分:0)
您是否在localhost:3000上运行了其他应用程序?因为如果没有,那么你的服务器所做的就是一次又一次地召唤自己,造成一个循环。
如果您确实有其他应用程序从数据库中提取用户,那么请确保它在其他端口上运行,而不是您的rails应用程序。
如果您只有1个应用,那么您就不需要休息客户端。
答案 2 :(得分:0)
你实际上可以做到这一点,没有任何额外的宝石。您只需根据要向API用户公开的内容声明路由,并相应地返回类型(xml,json,...)。