簡體   English   中英

Rails 4和AngularJS 1.3.x的406不可接受錯誤$ http.get

[英]406 Not Acceptable Error with Rails 4 and AngularJS 1.3.x $http.get

我在StackOverflow上查看了其他示例,但我仍然需要幫助。

我下面的問題是o.get函數通過其ID檢索單個帖子。

在調試時,我發現當我單擊正確的鏈接時實際上正在擊打此功能。 但是,單擊時拋出406 Not Acceptable錯誤。

我不確定這個問題是在角度上還是在我的表演動作上,也可以在下面找到。

這是我的服務代碼:

angular.module('hackerNews')
.factory('posts', ['$http',
    function($http) {
        var o = {
            posts: []
        };

    o.getAll = function() {
        return $http.get('/posts.json').success(function(data) {
            angular.copy(data, o.posts);
        });
    };

    o.create = function(post) {
        return $http.post('/posts.json', post).success(function(data) {
            o.posts.push(data);
        });
    };

    o.upvote = function(post) {
        return $http.put('/posts/' + post.id + '/upvote.json').success(function(data) {
            post.upvotes += 1;
        });
    };

    o.get = function(id) {
        return $http.get('/posts/' + id).then(function(res) {
            return res.data;
        });
    };

    o.addComment = function(id, comment) {
        return $http.post('/posts/' + id + '/comments.json', comment);
    };

    o.upvoteComment = function(post, comment) {
        return $http.put('/posts/' + post.id + '/comments' + comment.id + '/upvote.json')
        .success(function(data) {
            comment.upvotes += 1;
        });
    };
    return o;
}])

表演動作:

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

任何幫助將不勝感激。

謝謝!

編輯:

這是我的控制器中的內容:

這是我的應用程序控制器中的內容,我具有以下內容:

respond_to :json

大多數控制器如下:

class PostsController < ApplicationController

    def index
        respond_with Post.all
    end

    def create
        respond_with Post.create(post_params)
    end

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

    def upvote
        post = Post.find(params[:id])
        post.increment!(:upvotes)

        respond_with post
    end 

    private

    def post_params
        params.require(:post).permit(:link, :title)
    end
end

您需要在控制器頂部添加respond_to (帶有正在使用的格式列表),以使respond_with工作。 您可以在此處了解更多信息: http : //apidock.com/rails/ActionController/MimeResponds/respond_with

class PostsController < ApplicationController

  respond_to :json

  def index
    respond_with Post.all
  end

end

我遇到了同樣的問題。 我嘗試過的一種變通辦法是將'.json'添加到o.get函數中,如下所示:

o.get = function(id) {
  return $http.get('/posts/' + id + '.json').then(function(res) {
    return res.data;
  });
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM