r0man / ring-cors

Ring middleware for Cross-Origin Resource Sharing.
http://github.com/r0man/ring-cors
166 stars 44 forks source link

Possible to use middelware only on specific route? #3

Closed jacobemcken closed 10 years ago

jacobemcken commented 10 years ago

I would like to only apply this middleware on a route context called "/api".

Is that possible? An example would be awesome :)

r0man commented 10 years ago

As with all middleware, you have to add it to those routes you want. So don't add it to all your routes, only to the api routes.

On Tue, Apr 15, 2014 at 2:23 PM, Jacob Emcken notifications@github.comwrote:

I would like to only apply this middleware on a route context called "/api".

Is that possible? An example would be awesome :)

— Reply to this email directly or view it on GitHubhttps://github.com/r0man/ring-cors/issues/3 .

jacobemcken commented 10 years ago

All my "solutions" either apply CORS to all requests or none at all. Here is an example using Compojure (inspired by a question on stackoverflow) which I thought would work but it also applies CORS outside of the api context ie. routes defined in other-routes:

(defroutes api-routes*
   (context "/api" []
            api-routes1
            api-routes2))

(def api-routes
  (->
   #'api-routes*
   (cors/wrap-cors :access-control-allow-origin #"http://example.com")))

(defroutes app-routes
  api-routes
  other-routes
  (route/not-found "Page not found"))

(def ring-handler
  (-> app-routes
      compojure.handler/site))

Do you know how to apply the middleware to a specific route or context only? Or if you could point out some obvious things in the above I'm doing wrong I will research further... right now I'm kinda stuck :(

It would be awesome if a working example was available as part of the documentation.

r0man commented 10 years ago

This should apply CORS only to api-routes (api-routes1 and api-routes1) but not to other-routes. It doesn't?

jacobemcken commented 10 years ago

No it doesn't but the above example is just me stripping out stuff from my running application. I'll try create a simple piece of code to reproduce it... it might after all just be some other stuff interfering. I just assumed I was doing it wrong :-/

jacobemcken commented 10 years ago

I think I found an issue. See the repository: https://github.com/jacobemcken/testcors I have sample code to reproduce and written down all results in README.md. Search for the string "this is wrong", which marks the places where I think I found something :)

Let me know if I have misunderstood anything?

r0man commented 10 years ago

I pushed a fix. Can you please try it again with 0.1.1-SNAPSHOT?

jacobemcken commented 10 years ago

It works like a charm. Thanks man!