API POST请求返回404路由未找到

时间:2019-06-21 12:56:08

标签: ruby api post routes ruby-on-rails-5

Rails 5.2.2.1 ruby 2.6.3p62

我正在编写一个应该接受发布请求的API端点。我创建了路线:

namespace :api do
   scope module: :v1, constraints: Example::ApiVersionConstraint.new(1) do
     resources 'books', only: [:create]
   end
 end

bundle exec rails routes | grep books返回:

api_books POST /api/books(.:format) api/v1/books#create

app/controllers/api/v1/books_controller.rb

class Api::V1::BooksController < Api::BaseController
   attr_reader :book

   def create
      book = Book.build(title: 'test')

      if book.save
         render json: book
      else
         render json: { error: 'error' }, status: 400
      end
   end
end

服务器在端口3000上运行,并且使用邮递员向http://localhost:3000/api/books.json提交POST请求时,我得到以下响应:

{
"errors": [
    {
        "code": "routing.not_found",
        "status": 404,
        "title": "Not found",
        "message": "The path '/api/books' does not exist."
    }
],
"request": ""
}

lib/example/api_version_constraint.rb

module Example
  class ApiVersionConstraint

     def initialize(version)
        @version = version
     end

     def matches?(request)
        request.headers.fetch(:accept).include?("version=#{@version}")
     rescue KeyError
        false
     end
   end
end

为什么请求没有找到路线?

1 个答案:

答案 0 :(得分:1)

ApiVersionConstraint中可能出现故障。要进行故障排除,您可以执行以下操作:

 def matches?(request)
    byebug
    request.headers.fetch(:accept).include?("version=#{@version}")
 rescue KeyError
    false
 end

猜测标题的定位方式存在问题,因此可能会发生以下情况:

request&.headers&.fetch("Accept")&.include?("version=#{@version}")

因为有一个rescue子句,所以永远不会得到完整的错误;仅false,因此您可以尝试将其删除,看看是否出现更具描述性的错误。