首页 > 解决方案 > API POST 请求返回 404 route not found

问题描述

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 上运行,当使用 Postman 提交 POST 请求时,http://localhost:3000/api/books.json我得到以下响应:

{
"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

为什么请求找不到路由?

标签: rubyapipostroutesruby-on-rails-5

解决方案


某些东西可能会失败ApiVersionConstraint。要进行故障排除,您可以执行以下操作:

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

猜测这是您如何定位标题的问题,所以这样的事情可能会起作用:

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

因为你有一个rescue子句,你永远不会得到完整的错误;only false,因此您可以尝试删除它并查看是否收到更具描述性的错误。


推荐阅读