2017-03-07 51 views
0

我正在學習如何使用RoR編寫一個restful API並且有一個與它相關的問題。所以,我會解釋我與代碼一起做了什麼。帶欄杆的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,我已經包含了其他的客戶端也是如此。

gem 'rest-client' 

我的路線是: 根的員工#指數「 資源, '僱員'

希望一切都很好至今。

現在,當我送:

- >捲曲請求 'http://localhost:3000/employees',它卡住。

- >在'http://localhost:3000/'獲取請求(通過在瀏覽器中輸入),它也陷在這裏。

我失蹤的是什麼?

+0

'/ employess'命中EmployeesController#索引嗎? – Santhosh

+0

@Santhosh,是的,它擊中了那個。 –

+0

是不是一個無限循環? – Santhosh

回答

1

您不需要RestClient,因爲您正在此處編寫服務器,而不是客戶端。瀏覽器充當客戶端。刪除對本地主機的調用,因爲它正在創建一個循環。

的URL,這應該已經在你的routes.rb設置,也許使用:假設這是一個典型的應用

resources :users 

,展會功能應該從數據庫中使用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 
+0

我正在嘗試'捲曲'以及我想我會需要一個休息客戶端。合理? –

+0

@mahemoff,我不明白。爲什麼我要將'用戶'聲明爲資源? –

+0

如果您試圖製作從數據庫讀取用戶的標準服務,則無需捲曲。服務器從數據庫獲取數據,而不是其他服務。然後,您可以通過將瀏覽器指向http:// localhost:3000 – mahemoff

0

你有一些其他的應用程序在localhost:3000上運行嗎?因爲如果沒有,那麼你的服務器一次又一次地調用自己,造成一個循環。

如果你確實有一些其他應用程序,它從數據庫中提取用戶,那麼確保它運行在其他一些端口上,而不是你的rails應用程序。

如果你只有1個應用程序,那麼你不需要休息客戶端。

0

你實際上可以做到這一點,沒有任何額外的寶石。您只需根據要公開給API用戶的聲明來聲明路由,並相應地返回類型(xml,json,...)。