groovy - 在 Ratpack 中使用 `prefix {}` 方法而不是 `all { byMethod { } }` 会导致 405 Method Not Allowed - 出了什么问题?
问题描述
我刚刚开始阅读“Learn Ratpack”,在本书一开始的一个例子中,作者使用'all','byMethod','get'和'post'来举例说明如何解析请求数据,他的工作方式,但我尝试使用'prefix','get'和'post',但我无法得到相同的结果,它返回405-Method Not Allowed。
我试图在文档中找到一些东西,但我不明白为什么带有“前缀”的行为。
示例版本
import static ratpack.groovy.Groovy.ratpack
import ratpack.form.Form
ratpack {
handlers {
all {
byMethod {
get {
//In the exemple he sends a html form
}
post {
//And here he parses it.
}
}
}
}
}
405版
import static ratpack.groovy.Groovy.ratpack
import ratpack.form.Form
ratpack {
handlers {
prefix("parsing-request-data") {
get{
//From here all the same
就是这样,我错过了什么?
解决方案
如果你想对同一个相对路径使用多个不同的 HTTP 方法,你仍然需要使用byMethod {}
方法创建这样的处理程序。否则,链中与相对路径匹配的第一个处理程序处理请求,它可能会失败或成功。(在您的情况下,POST 请求因405 Method Not Allowed而失败,因为get
处理程序处理请求并且在请求中发现了不正确的 HTTP 方法。如果您希望看到 GET 请求失败而不是 POST one - 重新排序方法,因此post {}
是链中的第一个处理程序。)
该byMethod {}
方法允许为同一个相对路径注册多个处理程序,这些处理程序将根据请求的 HTTP 方法进行解析。在使用prefix {}
方法的情况下,您可以访问辅助方法byMethod {}
中的方法:path {}
import static ratpack.groovy.Groovy.ratpack
ratpack {
handlers {
prefix("parsing-request-data") {
path {
byMethod {
post {
response.send("A response returned from POST /parsing-request-data\n ")
}
get {
response.send("A response returned from GET /parsing-request-data\n")
}
}
}
get("test") {
response.send("A response returned from GET /parsing-request-data/test\n")
}
}
}
}
还有一些 curl 命令来测试它:
$ curl -i -X GET http://localhost:5050/parsing-request-data
HTTP/1.1 200 OK
content-type: text/plain;charset=UTF-8
content-length: 51
A response returned from GET /parsing-request-data
$ curl -i -X POST http://localhost:5050/parsing-request-data
HTTP/1.1 200 OK
content-type: text/plain;charset=UTF-8
content-length: 53
A response returned from POST /parsing-request-data
$ curl -i -X GET http://localhost:5050/parsing-request-data/test
HTTP/1.1 200 OK
content-type: text/plain;charset=UTF-8
content-length: 56
A response returned from GET /parsing-request-data/test
推荐阅读
- ssrs-2012 - 检查一个值在 SRSS 中是否有数据
- c - 未定义联合名称时访问 uino 变量
- android - 如何为应用启用降级?
- django - 相关模型的 Django 查询
- android - 当我尝试在颤振中使用 Facebook 登录时,在根项目“连接”中找不到任务“assembleAarRelease”
- firebase - 使用 Firebase 实现 Dialogflow
- javascript - 如何在VS代码中将单行跨越成多行?
- c# - 在 C# 中引用来自不同文件夹的类
- python - 数据框中两个对象之间的 T 检验
- node.js - 下一个 js:错误中间件正在返回 res.status 未定义