ruby - 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
为什么请求找不到路由?
解决方案
某些东西可能会失败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
,因此您可以尝试删除它并查看是否收到更具描述性的错误。
推荐阅读
- geolocation - 是否有可能来自同一网络的 3 个 IP 地址来自不同的国家?
- android - 如何将投射按钮实现为浮动操作按钮?
- sql - ORA-00936: 缺少使用提示的表达式
- javascript - 如何对 AWS 托管后端进行 HTTPS 调用
- javascript - Firebase - 获取最后一个子 Javascript 的第一个值
- java - javaFx应用程序需要圆形滑块
- python - Flask Caching 文件系统缓存是否跨进程共享?
- python - 在xml,Python中使用if条件嵌套for循环
- javascript - 标准输出中的NodeJS child_process ansi
- node.js - 通过在猫鼬中不使用填充进行分组