【问题标题】:Error while building an Json api : No route matches [GET] "/v1/posts构建 Json api 时出错:没有路由匹配 [GET] "/v1/posts
【发布时间】:2016-06-14 08:08:15
【问题描述】:

我正在尝试为我的应用程序构建一个 json api

这是我的 ROUTES.RB 文件

Rails.application.routes.draw do
mount RailsAdmin::Engine => '/admin', as: 'rails_admin'
devise_for :users
namespace :api , :path =>"", :constraints => {:subdomain =>"api"} , defaults: {format: 'json'} do

namespace :v1 do
  resources :posts do
   resources :comments
  end
 end
end

 #  namespace :v1 do
 #   resources :posts, only: [:index]
  #end  
          #end

root 'posts#index'

end

我在 Controller 下创建了另一个文件夹来使用命名空间

我在 v1 文件夹下创建了“api”文件夹,并在该文件夹下创建了一个 posts_controller.rb 文件 这是确切的路径 " /app/controllers/api/v1/posts_controller.rb "

     class Api::V1::PostsController < ApplicationController

       protect_from_forgery with: :null_session
       before_action :destroy_session

      def index
        @posts=Post.all

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

      end

      private
       def destroy_session
       request.session_options[:skip]= true
     end


   end

我确实在帖子控制器中有数据,并且也建立了关联。

其实我需要的是,当我访问这个 Url http://api.localhost:3000/v1/posts 我需要帖子中的数据,就像浏览器中的 json 格式一样

但它显示此错误

没有路线匹配 [GET] "/v1/posts"

我该如何解决这个错误?

【问题讨论】:

    标签: ruby-on-rails ruby json api


    【解决方案1】:

    您已经直接定义了您的:posts 资源,并将其命名为api > v1。您可以访问http://api.localhost:3000/posts,但无法访问v1 下的内容。您需要像这样向它添加命名空间

    namespace :v1 do
      resources :posts do
        resources :comments
      end
    end
    

    您所做的是在api 中命名了v1。您可以采取上述方法或尝试访问http://api.localhost:3000/api/v1/posts

    更新:

    Rails.application.routes.draw do
      mount RailsAdmin::Engine => '/admin', as: 'rails_admin'
      devise_for :users
    
      namespace :api, defaults: {format: 'json'} do
        namespace :v1 do
          resources :posts do
            resources :comments
          end
        end
      end
    
      #The below part to access everything the regular way(non-api way)
      resources :posts do
        resources :comments
      end
    
     #namespace :v1 do
     #  resources :posts, only: [:index]
     #end  
     #end
    
     root 'posts#index'
    
    end
    

    将您的路线文件更新为以下内容。并尝试访问这两个网址

    http://localhost:3000/posts

    http://localhost:3000/api/v1/posts

    如果没有额外的配置,您将无法访问本地主机中的子域。所以试试新的路线代码,不要在你的路线中使用constraints

    【讨论】:

    • 我按你说的编辑了,但还是显示错误,我尝试访问api.localhost:3000/api/v1/posts,但它也显示“路由错误”
    • 是同一个路由错误吗?您可以使用新内容更新您问题的路由器文件吗?
    • 如你所说已更新,现在我遇到更多错误,也无法访问 localhost:3000/posts !!
    • 第一个网址有效,但第二个网址给出“错误”没有路由匹配[GET]“/api/v1/posts”
    • 您是否从您的 api 命名空间中删除了 api 子域和约束?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-26
    • 2016-05-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多