Post API 使用 Ratpack 和 Groovy 给出 405 错误和 RxJava 方法不工作

Post API using Ratpack and Groovy giving 405 Error and RxJava methods not working

我正在使用 RatpackGroovy 构建一个 API。 POST API 总是给出:

405-Method not Found Error

这是来自 POST 端点处理程序的片段。在这段代码中,promiseSinglethenobservemapdoOnNextdoOnError

RxJAVA 函数不工作。 RxJava 方法不起作用有什么原因吗?

saveJsonAsData(context, id)
            .promiseSingle()
            .then { Data updateddata ->
                context.response.headers
                    .add(HttpHeaderNames.LOCATION, "/api/save/${updateddata.id}/${updateddata.value}")
                context.response.status(HttpResponseStatus.CREATED.code())
                    .send()
            }
    }

    protected Observable<Data> saveJsonAsData(GroovyContext context, String id) {
        context.request.body.observe()
            .map { TypedData typedData -> extractData(context, typedData) }
            .doOnNext { Data data ->
                data.id = id
                validatorWrapper.validate(data)
            }
            .flatMap(data.&save as Func1)
            .doOnError { Throwable throwable -> log.error("Error saving data", throwable) }
    }

问题不在于 Rx,而在于 Context 的使用。

您应该尝试将响应处理逻辑保留在您的处理程序中,即不要传递上下文,而是获取您需要的对象并将它们传递给您的服务。

举个例子

path('myendpoint') { MyRxService service ->
  byMethod {
    get {
      // do something when request is GET
    }
    post {
      request.body.map { typedData ->
        extractItem(typeData) // extract your item from the request first
      }.flatMap { item ->
          service.saveJsonAsItemLocation(item).promiseSingle() // then once it's extracted pass the item to your "saveJsonAsItemLocation" method
      }.then { ItemLocationStore updatedItem ->
          response.headers.add(HttpHeaderNames.LOCATION, "/itemloc/v1/save/${updatedItem.tcin}/${updatedItem.store}")
          context.response.status(HttpResponseStatus.CREATED.code()).send()
      }
    }
  }
}

我猜你有这样的东西:

get {
 // get stuff
}

post {
  // post stuff
}

这不起作用的原因是 Ratpack 不使用路由 Table 来处理传入请求,而是使用链委托。 get {} 绑定到根路径和 GET http 方法,post {} 绑定到根路径和 POST http 方法。因为 get {} 匹配路径,Ratpack 认为处理程序匹配并且由于处理程序用于 GET 它认为它是 405.

有可用的链方法,无论 HTTP 方法如何都可以绑定,例如 all {}path {}。 Chain#all 将处理 all 路径和方法,其中 Chain#path(String) 匹配特定路径。

希望对您有所帮助。