繁体   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