2016-05-20 22 views
1

我用純JavaScript前端模板通過JSON API禁用HTML格式的響應整個Rails應用程序

不過來處理與Rails的所有請求,

我不知道爲什麼有時異常會給我的錯誤HTML格式的消息。

因爲我已經設定的API請求格式的JSON

控制器(我只保留format.json控制器)

format.json { render json: @city.errors, status: :unprocessable_entity } 

Route.rb

namespace :api do 
    namespace :v1, defaults: {format: 'json'} do 
    resources country do 
     resources city do 
      ..... 
     end 
    end 
    end 
    end 
+0

你爲什麼不使用葡萄和揚鞭建立自己的API我的朋友。參考:https://github.com/ruby-grape/grape,https://github.com/ruby-grape/grape-swagger-rails。希望這個幫助。 :) – thanhnha1103

回答

1

我不知道爲什麼有時例外會給我HTML格式的錯誤 消息。

它不依賴於你的應用程序,它是關於請求和請求標題,如果有人提出請求作爲html rails試圖呈現html。

1

異常在您的控制器之外的html中呈現。你應該自己做這件事:

控制器:

begin 
    code_for_ok 
rescue #some exception 
    render json: @city.errors, status: :unprocessable_entity 
end 
+0

我認爲這裏的例外是'ActionController :: UnknownFormat'。 –