【问题标题】:Rails API: 406 Not Acceptable in 20msRails API:406 在 20 毫秒内不可接受
【发布时间】:2014-09-17 06:53:22
【问题描述】:

我正在尝试为 RoR 应用构建 API。我有以下内容:

  1. app/controllers/api/base_controller.rb:

    module Api
      class BaseController < ApplicationController
        respond_to :json
      end
    end
    
  2. app/controllers/api/orders_controller.rb

    module Api
      class OrdersController < Api::BaseController
    
        def get_orders
            os = Order.last
            @order = Hash.new
            @order["number"] = os.number
            @order["id"] = os.id
            respond_to do |format|
                format.json { render json: @order }
            end
        end
      end
    end
    
  3. config/routes.rb

    namespace :api do
      match "/get_orders" => "orders#get_orders"
    end
    

但是当我转到“localhost:3000/api/get_orders”时,我得到一个406

在 2014-09-17 12:19:40 开始 GET "/api/get_orders" for 127.0.0.1 +0530 标签加载 (170.5ms) SELECT DISTINCT(tags.tag_name) FROM "tags" WHERE (tags.taggable_type = 'Product') 处理方式 Api::OrdersController#get_orders 作为 HTML 订单加载 (0.4ms) SELECT "orders".* FROM "orders" ORDER BY "orders"."id" DESC LIMIT 1 已完成 406 在 24 毫秒内不可接受

我该如何解决这个问题?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3


    【解决方案1】:

    在您的控制器中,行

    respond_to :json
    

    意味着它应该响应使用 JSON 格式的请求。如果您请求任何其他格式(例如 HTML),您将收到 406 Not Acceptable。

    尝试使用 JSON 扩展请求页面:

    localhost:3000/api/get_orders.json
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-17
      • 2017-08-23
      • 2013-12-18
      • 2015-06-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多