简体   繁体   English

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

[英]Rails 5 API - How to respond with HTML on a specific controllers as an exception?

I have Rails API app. 我有Rails API应用程序。 And 99% of the routes are JSON routes. 并且99%的路由是JSON路由。 however, I want to add one single route that will response with HTML. 但是,我想添加一条将用HTML响应的路由。 How can I do that? 我怎样才能做到这一点?

This is my current setup and when I browse the route I see a string of HTML tags on the screen. 这是我当前的设置,当我浏览路线时,在屏幕上看到一串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

Any ideas? 有任何想法吗?

According to the Layouts and Rendering Guide : 根据版式和渲染指南

When using html: option, HTML entities will be escaped if the string is not marked as HTML safe by using html_safe method. 当使用html:选项时,如果使用html_safe方法将该字符串未标记为HTML安全,则HTML实体将被转义。

So you just need to tell it the string is safe to render as 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

Most new APIs only need to serve JSON, yet it is common to see respond_to in API controllers. 大多数新API只需要提供JSON,但在API控制器中通常看到respond_to Here is an example: 这是一个例子:

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

We can drop the respond_to , but if you hit the url without .json you'll see it thinking you're using HTML in the logs 我们可以删除respond_to ,但是如果您在不带.json的情况下访问url,则会看到它以为您在日志中使用HTML

Processing by PeopleController#index as HTML

If you want your route to respond as HTML, you can default that in the route to HTML 如果您希望您的路线以HTML格式进行响应,则可以将其默认设置为HTML

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

So you can drop the respond_to and let it have its curse, then default your route to take effect as HTML. 因此,您可以放下respond_to并使其具有诅咒,然后默认将您的路由作为HTML生效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM