代码之家  ›  专栏  ›  技术社区  ›  Ilya Libin

Rails 5 API-如何在特定控制器上以HTML作为异常响应?

  •  2
  • Ilya Libin  · 技术社区  · 7 年前

    我有Rails API应用程序。99%的路由是JSON路由。但是,我想添加一个将用HTML响应的路由。我该怎么做?

    这是我当前的设置,当我浏览路线时,我会在屏幕上看到一串HTML标记。

    class ApplicationController < ActionController::API
       include ActionController::MimeResponds      
    end
    
    class DocumentPublicController < ApplicationController
      respond_to :html
    
      def show
        html = "<html><head></head><body><h1>Holololo</h1></body></html>"#, :content_type => 'text/html'
        respond_to do |format|
          format.html {render html: html, :content_type => 'text/html'}
        end
      end
    end
    

    有什么想法吗?

    2 回复  |  直到 7 年前
        1
  •  2
  •   Simple Lime    7 年前

    根据 Layouts and Rendering Guide :

    使用html:option时,如果字符串未使用html\u safe方法标记为html安全,则将转义html实体。

    因此,您只需告诉它字符串可以安全地呈现为html:

    # modified this line, though could be done in the actual render call as well
    html = "<html><head></head><body><h1>Holololo</h1></body></html>".html_safe
    
    respond_to do |format|
      format.html {render html: html, :content_type => 'text/html'}
    end
    
        2
  •  0
  •   Ilya Libin    7 年前

    大多数新的API只需要提供JSON,但这是常见的 respond_to 在API控制器中。以下是一个示例:

    def show
      html = "<html><head></head><body><h1>Holololo</h1></body></html>"
      respond_to do |format|
        format.html { render :json => html }
      end
    end
    

    我们可以放弃 respond\u to ,但如果您在没有的情况下点击url。json您会看到它认为您在日志中使用HTML

    Processing by PeopleController#index as HTML
    

    如果希望路由响应为HTML,可以在路由到HTML中默认设置为HTML

    namespace :api, :defaults => {:format => :html} do
      namespace :v1 do
        resources :people
      end
    end
    

    所以你可以放下 respond\u to 让它有它的诅咒,然后默认您的路由作为HTML生效。