当发送 header 'Content-type: application/json' 时,Rails 会在多个级别更改行为:
如果我不能信任(外部)客户端传递正确的 header 怎么办?换句话说,我想让我的应用程序表现得好像客户端总是传递 'Content-type: application/json' header ,即使客户端实际上没有?
最佳答案
您可以使用在操作中设置类型
request.format = :json
我测试它使用
class ExampleController < ApplicationController
def always_accept_json
request.format = :json
respond_to do |format|
format.json { raise "HEY" }
format.html
end
end
end
您可以在 Any ActionController 中的任何位置执行此操作,即如果您希望在顶层将所有请求显示为 content_type
application/json
只需将其设为 application_controller.rb
上的过滤器即可那套request.format
关于ruby-on-rails - 如何让 Rails 将发布的字符串解析为 json 而不发送 'Content-type: application/json' header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12915653/