Rails 4 - 仅响应 JSON 而不是 HTML [英] Rails 4 - Respond only to JSON and not HTML

查看:50
本文介绍了Rails 4 - 仅响应 JSON 而不是 HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 rails 4 中构建 API,但在使用 respond_to :json 并尝试访问 html 版本时,rails 返回 500 错误而不是 406 错误.

I'm trying to build an API in rails 4, and am having an issue where rails returns a 500 error instead of a 406 when using respond_to :json and trying to access the html version.

这是一个演示问题的示例控制器:

Here's an example controller demonstrating the problem:

class PostsController < ApplicationController
  respond_to :json

  def index
    @posts = Post.all
  end
end

我还有一个用于 index 的 jbuilder 视图,它在通过 JSON 访问时有效.如果我尝试访问没有 JSON 扩展名的路由,它会尝试加载 HTML 模板(不存在)并返回 500 错误,而不是仅呈现 JSON 或返回 406 错误.

I also have a jbuilder view for index that works when accessing via JSON. If I try accessing the route without the JSON extension, It attempts to load the HTML template (which doesn't exist) and returns a 500 error, instead of just rendering JSON or returning a 406 error.

可能是什么原因造成的?为任何帮助干杯.

What could be causing this? Cheers for any help.

推荐答案

我相信这里有两个部分:
1)在rails
中只有json请求2) json 仅 responses 在 rails

I believe there are 2 parts here:
1) json only requests in rails
2) json only responses in rails

1) 配置您的应用程序控制器以确保仅json 请求

1) Configure your application controller to ensure json requests only

# app/controller/application_controller.rb  
before_action :ensure_json_request  

def ensure_json_request  
  return if request.format == :json
  render :nothing => true, :status => 406  
end  

2) 配置您的 Rails API 路由以确保仅 json 响应

2) Configure your Rails API routes to ensure json responses only

# config/routes.rb  
MyApp::Application.routes.draw do  
  namespace :api, constraints: { format: 'json' } do  
    namespace :v1 do  
      resources :posts  
    end  
  end  
end  

这篇关于Rails 4 - 仅响应 JSON 而不是 HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆