How to enable CORS in Grails 3.0.1

后端 未结 7 1356
有刺的猬
有刺的猬 2021-02-18 22:45

I would like to do cross origin communication using Grails in server side. The only documentation that I found is this one

https://grails.org/plugin/cors

but thi

7条回答
  •  故里飘歌
    2021-02-18 22:53

    I was playing around with the emberjs framework together with a Grails 3.0 rest application when I was hit by the CORS issue. Following the steps in this article http://www.greggbolinger.com/rendering-json-in-grails-for-ember-js/ helped me get further.

    The article shows how you can use the new Interceptors to create a CorsInterceptor class which sets the correct headers.

    class CorsInterceptor {
    
      CorsInterceptor() {
        matchAll()
      }
    
      boolean before() {
        header( "Access-Control-Allow-Origin", "http://localhost:4200" )
        header( "Access-Control-Allow-Credentials", "true" )
        header( "Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE")
        header( "Access-Control-Max-Age", "3600" )
        true
      }
    
      boolean after() { true }
    }
    

    This worked as expected for GET requests, but failed for POST and PUT requests. The reason for this was that an OPTIONS preflight request was sent first to http://localhost:8080/mycontroller/1234, which in my case caused a 404 not found to be returned.

    With the help from this answer https://stackoverflow.com/a/31834551 I modified the CorsInterceptor class to this instead:

    class CorsInterceptor {
    
       CorsInterceptor() {
        matchAll()
      }
    
      boolean before() {
        header( "Access-Control-Allow-Origin", "http://localhost:4200" )
        boolean options = ("OPTIONS" == request.method)
        if (options) {
    
            header( "Access-Control-Allow-Origin", "http://localhost:4200" )
            header( "Access-Control-Allow-Credentials", "true" )
            header( "Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE")
            header( "Access-Control-Max-Age", "3600" )
    
            response.status = 200
        }
    
        true 
      }
    
      boolean after() { true }
    
    }
    

    Now POST and PUT requests were working.

提交回复
热议问题