【发布时间】:2018-08-15 12:00:52
【问题描述】:
TLDR:
使用rails --api,预期的rails从POST and params[:_method]='put'路由为PUT方法,但路由为POST
给定:
- 导轨 4.2.8
- rails-api 0.4.1
考虑以下几点:
config/routes.rb:
resources :sessions, do
put 'authenticate', on: :collection
end
一些客户端 HTML 文件:
<form action='http://localhost:3000/sessions/authenticate' method='post'>
<input type='hidden' name='_method' value='put'>
...
</form>
...提交表单时:
rails server 输出:
Started POST "/sessions/authenticate" for ::1 at 2018-03-07 11:20:21 +0000
No route matches [POST] "/sessions/authenticate" excluded from capture: DSN not set
ActionController::RoutingError (No route matches [POST] "/sessions/authenticate"):
actionpack (4.2.8) lib/action_dispatch/middleware/debug_exceptions.rb:21:in `call'
actionpack (4.2.8) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
...
Inspecting Chrome -> Developer Tools -> Network tab -> [REQUEST],payload正确如下图:
常规
请求网址:http://localhost:3000/sessions/authenticate
...表单数据
_方法:放置
...
疑难解答
- 我尝试在一个新的 Rails 项目中复制确切的代码,但这次没有使用
--api模式,并且请求有效:它正确识别了_method='PUT'并路由为PUT。所以,我有一种感觉,这与普通 rails 和 api 模式之间的一些差异有关。不幸的是,经过多次搜索,我找不到任何解决方案。
任何帮助将不胜感激。
【问题讨论】:
-
你使用什么 gem/package/... 来查询你的端点?
-
@Ben 我刚刚更新了我的问题以包括
rails-api 0.4.1。但是,如果您在谈论“发布”本身的表单,我没有使用任何东西,它只是一个简单的.html文件。 -
好的,我明白了;显然答案成功了;之所以问,是因为我倾向于使用 axios 或相关工具查询 rails 端点;只需指定 PUT 或 PATCH 方法,它们就可以像魅力一样工作
-
@Ben 哦,我看到像
postman?是的,指定PUT作为 HTTP 方法在 Postman 中有效,但指定POST和_method='put'在 Postman 中无效。但是谢谢你的帮助!!! :) -
是的,sergio 确实提供了一个准确的解决方案;这里需要 rails_api (: