【问题标题】:Completed 406 Not Acceptable error when attempting Angular.js query() function尝试 Angular.js 查询()函数时完成 406 Not Acceptable 错误
【发布时间】:2014-04-17 01:47:01
【问题描述】:

我想使用 Angular.js 和 Rails 显示卡片索引。

这是我的代码。

# app/views/decks/show.html.erb
<div ng-controller="DeckCtrl">
  <form ng-submit="addCard()">
    <input type="text" ng-model="newCard.front" />
    <input type="submit" value="Add">
  </form>
  {{newCard.front}}
  <ul>
    <li ng-repeat="card in cards">
      {{card.front}}
    </li>
  </ul>
</div>

还有咖啡脚本

# app/assets/javascripts/decks.js.coffee
app = angular.module("Deck", ["ngResource"])

@DeckCtrl = ($scope, $resource) ->
  Card = $resource("/cards/:id", {id: "@id"}, {update: {method: "PUT"}})
  $scope.cards = Card.query()

  $scope.addCard = ->
    $scope.cards.push($scope.newCard)
    $scope.newCard = {}

还有CardsController

class CardsController < ApplicationController
  respond_to :json
  def index
    respond_with Card.all
  end

  def show
    respond_with Card.find(params[:id])
  end

  def create
    respond_with Card.create(card_params)
  end

  def update
    respond_with Card.update(params[:id], card_params)
  end

  def destroy
    respond_with_Card.destroy(params[:id])
  end

  private
    # Never trust parameters from the scary internet, only allow the white list through.
    def card_params
      params.require(:card).permit(:front, :back, :tips, :cardtype, :deck_id, :box_number)
    end
end

addCard 函数正在运行,但 Card.query() 给我这个错误。

Started GET "/cards" for 127.0.0.1 at 2014-04-17 10:39:42 +0900
Processing by CardsController#index as HTML
Completed 406 Not Acceptable in 2ms

ActionController::UnknownFormat - ActionController::UnknownFormat:

看起来Angular.js 发送HTML 而不是json,这会导致错误,对吗? 如何消除此错误?

【问题讨论】:

    标签: javascript ruby-on-rails angularjs


    【解决方案1】:

    406 表示服务器不支持客户端请求的格式。

    angular 发送的默认Accept header 是application/json, text/plain, */*。所以基本上它接受一切。 $resource不会改变任何东西,据我所知。

    很可能在您的应用程序中的某个地方设置了您的服务器无法处理的格式。

    【讨论】:

    • 你知道格式是在哪里配置的吗?只是猜测会有所帮助。我不知道它在哪里。至少config/application.rb中没有条目
    • 我解决了这个问题!我将config/routes.rb 中的resources :cards 更改为resources :cards, defaults: {format: :json}。那么它现在可以工作了,谢谢!
    【解决方案2】:

    试试这个?

    $resource("/cards/:id", {id: "@id"}, {update: {method: "PUT", responseType: 'json'}})
    

    【讨论】:

      猜你喜欢
      • 2013-08-10
      • 1970-01-01
      • 2016-02-21
      • 2014-11-12
      • 2020-07-26
      • 2021-01-21
      • 2012-07-23
      • 2014-02-21
      • 2012-01-01
      相关资源
      最近更新 更多