【问题标题】:Get json response without specifying '.json in URL'在不指定 '.json in URL' 的情况下获取 json 响应
【发布时间】:2016-01-30 06:48:23
【问题描述】:

我正在开发 Rails + AngularJS 应用程序。为了访问我的应用程序的 json 响应,我必须在我的角度 $resource url 中使用 /something.json 而不仅仅是 /something

有办法解决吗?

路线

upvote_post_comment PUT  /posts/:post_id/comments/:id/upvote(.:format) comments#upvote
      post_comments POST /posts/:post_id/comments(.:format)            comments#create
       post_comment GET  /posts/:post_id/comments/:id(.:format)        comments#show
        upvote_post PUT  /posts/:id/upvote(.:format)                   posts#upvote
              posts GET  /posts(.:format)                              posts#index
                    POST /posts(.:format)                              posts#create
               post GET  /posts/:id(.:format)                          posts#show
                    GET  /                                             home#index

PostsController

class PostsController < ApplicationController
    def index
        @posts = Post.all

        respond_to do |format|
            format.json { render json: @posts }
        end
    end
end

Angular 服务提供者

angular.module('flapperNews')
.factory('posts', ['$resource', function($resource) {
    return $resource('/posts.json/:id', {id: "@id"})
}]);

【问题讨论】:

  • 我认为您可以简单地将 + '.json' 添加到第一个参数
  • 我不相信他想要在他的 Angular 应用程序中添加 .json 扩展?
  • 它不起作用, .json 在 url 中意味着您正在访问的资源不是将内容类型返回为 json ,而是返回一个 html。所以尝试将你服务器的内容类型设置为“application/json”然后看看。

标签: javascript ruby-on-rails json angularjs routes


【解决方案1】:

在您的控制器中,您通过 respond_do 说,仅当格式 (.:format) in the routes 指定为 json 时才给出 json 响应。

您可以修改您的控制器 PostsController 以响应 json 格式,无论格式是什么。

class PostsController < ApplicationController
    def index
        @posts = Post.all
        render json: @posts
    end
end

注意:在此之后,url 之后的格式将不再重要(无论是 .json、.xml,什么都没有)。控制器的操作将始终返回 json。

【讨论】:

    【解决方案2】:

    尝试在网址末尾添加.json

    angular.module('flapperNews')
    .factory('posts', ['$resource', function($resource) {
        return $resource('/posts/' + id + '.json')
    }]);
    

    【讨论】:

      【解决方案3】:

      在 routes.rb 中设置默认格式

      resources :posts, defaults: { format: :json }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-06
        • 1970-01-01
        • 2013-12-04
        • 2018-11-26
        • 2021-09-02
        相关资源
        最近更新 更多