【发布时间】:2023-03-05 21:27:02
【问题描述】:
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 向 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
为什么请求找不到路由?
【问题讨论】:
-
能否请您发布在
Example::ApiVersionConstraint中定义的限制? -
constraints: Example::ApiVersionConstraint.new(1)-- 大概这是失败的。但它有什么作用?请提供minimal reproducible example。 -
@NMPennypacker 更新了问题以包含 apiversionconstraint 文件
-
这就是问题所在。感谢您的帮助。在邮递员的标题选项卡中,我必须包含带有值 version=1 的 Accept
标签: ruby api post routes ruby-on-rails-5