How to setup `cors` on Yesod without scaffold structure?

161 Views Asked by At

There is clear doc on enable CORS in yesod https://github.com/yesodweb/yesod-cookbook/blob/master/cookbook/Allowing-WOFF-fonts-to-be-accessed-from-other-domains-%28CORS%29.md#using-wai-cors-package

but it requires to run in a scaffold yesod application which has makeApplication and Application.hs

In my cases, the code base was built not by yesods scaffold now try to be exposed as a RESTful service.

mkYesod "App" [parseRoutes|
 /Hello HelloR POST OPTIONS
 /version VersionR GET
|]

How to add CORS support in this case ?

Ref:

1

There are 1 best solutions below

0
Shawn Zhang On BEST ANSWER

Here is the code how I solve this.

Using toWaiApp to extract the application instance and wrap it with cors midddle ware.

mkYesod "App" [parseRoutes|
 /Hello HelloR POST OPTIONS
 /version VersionR GET
|]

main :: IO ()
main =
   do
     app <- toWaiApp App
     run 8081 $ defaultMiddlewaresNoLogging $ cors (const $ Just $ simpleCorsResourcePolicy { corsOrigins = Nothing , corsMethods = ["OPTIONS", "GET", "PUT", "POST"] , corsRequestHeaders = simpleHeaders }) $ app