gpt4 book ai didi

rest - 存在Content-Type:application/x-www-form-urlencoded header 时,Grails RestfulController不使用JSON进行响应

转载 作者:行者123 更新时间:2023-12-02 14:29:56 26 4
gpt4 key购买 nike

我正在尝试为我的应用程序实现一个简单的RestfulController。
给定以下域类:

class Test {
String name
int someInteger

static constraints = {
}
}

及其 Controller :
class TestController extends RestfulController<Test>{
TestController() {
super(Test)
}
}

在conf / UrlMappings.groovy中,我添加了以下条目:
"/api/$controller?(.${format})?" {
action = [POST: "save", PUT: "save", GET: "index", DELETE:"error"]
}

"/api/$controller/$id?(.${format})?" {
action = [POST: "update", PUT: "update", GET: "show", DELETE: "delete"]
}

获取请求工作正常,但是当存在 http://localhost:8080/app/api/test.json header 时,将请求发送和发送到 Content-Type: application/x-www-form-urlencoded之类的URL时,无法按预期方式以JSON响应。而是在保留已发送的条目之后渲染show action View 。

我也尝试使用Header Accept: application/json无效。

我该如何解决?

编辑:

进一步研究 RestfulController的源文件和有关 Content Negotiation的docs部分,我可以通过覆盖保存和更新方法替换该行来修复它:
request.withFormat {

与:
withFormat {

这是故意的还是 RestfulController的实现存在缺陷?
为什么它考虑使用Content-Type header 而不是Accept header 来呈现响应?

最佳答案

如果所有 Controller 的方法始终以JSON响应(当有响应正文时)是可以接受的,则可以使用responseFormats来实现,如下所示:

class TestController extends RestfulController<Test>{

static responseFormats = ['json']

TestController() {
super(Test)
}

def customJsonAction() {
respond Something.get(params.id)
}

def someActionThatRendersGsp() {
render view: 'myGsp', model: [foo: 'bar']
}
}

这意味着无论客户端发送了哪些 header ,参数等, Controller 都将始终以JSON进行响应。

关于rest - 存在Content-Type:application/x-www-form-urlencoded header 时,Grails RestfulController不使用JSON进行响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38283580/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com