首页 > 解决方案 > 在 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

就是这样,我错过了什么?

标签: groovyratpack

解决方案


如果你想对同一个相对路径使用多个不同的 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


推荐阅读