我想将此自定义 header 添加到我的其余API的每个响应中:

"customHeader": "foo"

为此,我创建了与所有 Controller 匹配的grails拦截器,并允许我修改请求。
class FooInterceptor {

    FooInterceptor() {
        matchAll()
    }

    boolean before() { true }

    boolean after() {
        header 'customHeader', "foo" //first try
        response.addHeader 'customHeader', "foo" //second try to do the same
        response.setHeader 'customHeader', "foo" //third try, setHeader doesn't work either
        true
    }

    void afterView() {
    }
}

我已经调试,可以看到 Controller 响应后调用了after方法:
respond([status:dodes.OK], [:])

我可以清楚地看到我的拦截器已被调用,并且addHader不会引发任何异常,但是我的 header 只是没有添加到最终响应中。

我的猜测是, chalice 的响应方法可能以某种方式“锁定”了响应,因此无法在之后添加 header ,但我不确定。

如何使用拦截器向Grails 3上的每个响应添加 header ?

最佳答案

以下对我有用。您可能需要使用before()代替。

class FooInterceptor {

    FooInterceptor() {
        match controller: '*', action: '*'
    }

    boolean before() {
        response.setHeader('customHeader', "foo")
        true
    }

    boolean after() { true }

    void afterView() {
      // no-op
    }
}

关于grails - 在grails 3 inceptceptor中的每个请求上添加响应 header ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58338610/

10-11 22:25
查看更多