简体   繁体   English

在整个Rails应用程序中禁用HTML响应格式

[英]Disable HTML respond format in whole Rails App

I use pure javascript frontend template to handle all requests with Rails via JSON API 我使用纯JavaScript前端模板通过JSON API处理所有与Rails的请求

However, 然而,

I don't know why sometimes the exception will give me the error message in HTML format. 我不知道为什么有时异常会以HTML格式给我错误消息。

Because I've already set the API request format in JSON 因为我已经在JSON中设置了API请求格式

Controller (I only keep format.json in the controller) 控制器(我只在控制器中保留format.json)

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

Route.rb Route.rb

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

I don't know why sometimes the exception will give me the error message in HTML format. 我不知道为什么有时异常会以HTML格式给我错误消息。

It's not dependent on your app, it is all about the request and request headers, if somebody make a request as html rails try to render html. 它不依赖于您的应用程序,而是与请求和请求标头有关的所有内容,如果有人在html rails尝试呈现html时发出了请求。

Exceptions are rendered in html outside of your controller. 异常在控制器外部以html呈现。 You should do it by yourself: 您应该自己做:

your controller: 您的控制器:

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

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

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