CORS handler

classic Classic list List threaded Threaded
9 messages Options
Reply | Threaded
Open this post in threaded view
|

CORS handler

der3k
Hello,
I am trying to run REST server that would support CORS (Cross-Origin Resource Sharing).

Here is what I have currently...

ratpack {
  handlers {
    handler {
      response.addHeader 'Access-Control-Allow-Origin', '*'
      response.addHeader 'Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE'
      response.addHeader 'Access-Control-Allow-Headers', 'Content-Type,X-Requested-With'
      next()
    }
    get ('projects') {
      def builder = new groovy.json.JsonBuilder()
      builder(projects: fetchProjects(projectsDir))
      response.send 'application/json', groovy.json.JsonOutput.prettyPrint(builder.toString())
    }
  }
}

This approach does not work. My AngularJS client is not able to retrieve JSON data. The 'OPTIONS' HTTP request returns correct headers, but status code is 405.

When I enter the 'projects' link directly into browser it works fine.

Any hints?

Thanks.
Reply | Threaded
Open this post in threaded view
|

Re: CORS handler

Luke Daley
Administrator
I've just added OPTIONS support: https://github.com/ratpack/ratpack/issues/187

If you build with the latest snapshot this should work.
Reply | Threaded
Open this post in threaded view
|

Re: CORS handler

Luke Daley
Administrator
In reply to this post by der3k
BTW, what is fetchProjects() doing? Is it connecting to a DB?
Reply | Threaded
Open this post in threaded view
|

Re: CORS handler

der3k
In reply to this post by Luke Daley
thanks for answer, I would check it :-)
Reply | Threaded
Open this post in threaded view
|

Re: CORS handler

der3k
In reply to this post by Luke Daley
kind of, it is reading some files, fetches data and returns map...
Reply | Threaded
Open this post in threaded view
|

Re: CORS handler

Luke Daley
Administrator
In that case, you should do it in the background for better performance…

get ('projects') {
  background {
    fetchProjects(projectsDir)
  }.then {
    def builder = new groovy.json.JsonBuilder()
    builder(projects: it)
    response.send 'application/json', groovy.json.JsonOutput.prettyPrint(builder.toString())
  }  
}

See: http://www.ratpack.io/manual/current/backgrounding.html#backgrounding
Reply | Threaded
Open this post in threaded view
|

Re: CORS handler

der3k
Thanks for info, I appreciate it :-)
Reply | Threaded
Open this post in threaded view
|

Re: CORS handler

der3k
In reply to this post by Luke Daley
I have built ratpack localy from the latest sources and now it works! Thanks :-)
Reply | Threaded
Open this post in threaded view
|

Re: CORS handler

Luke Daley
Administrator
FWIW, the latest binary snapshot also has the changes you need.