我試圖在rails 4中構建一個API,並且在使用respond_to :json
並嘗試訪問html版本時,導致rails返回500錯誤而不是406的問題。Rails 4 - 只響應JSON而不是HTML
這裏有一個例子控制器,展示了這個問題:
class PostsController < ApplicationController
respond_to :json
def index
@posts = Post.all
end
end
我也有一個index
JBuilder的視圖通過JSON訪問時的作品。如果我嘗試訪問沒有JSON擴展名的路由,它會嘗試加載HTML模板(不存在)並返回500錯誤,而不是僅呈現JSON或返回406錯誤。
這可能是什麼原因造成的?歡呼任何幫助。
可能重複:http://stackoverflow.com/questions/14579774/respond-to-only-json-in-rails?rq=1 – Josh
我沒有看到這一點,但我想知道爲什麼它不't只使用'respond_to:json'設置 –
'respond_to:json'和'respond_with @ posts'正確響應* HTTP/1.1 406 Not Acceptable *在生產中給我。在開發中,你會得到一個「HTTP/1.1 500內部服務器錯誤」和一個「ActionController :: UnknownFormat」 – Leito