wai-cors icon indicating copy to clipboard operation
wai-cors copied to clipboard

Can we add example for `yesod` ?

Open yellowbean opened this issue 2 years ago • 2 comments

Can we add example for yesod ?

yellowbean avatar Jun 29 '22 07:06 yellowbean

I also think this would be nice to have in the official documentation. It took a bit of time for me to figure out myself. I'll post a code-snippet here in case anyone else is curious.

import qualified Network.Wai as WAI
import Network.Wai.Handler.Warp (run)
import Network.Wai.Middleware.Cors (CorsResourcePolicy (..), cors, simpleCors, simpleCorsResourcePolicy, simpleHeaders)
import Yesod (Application, defaultMiddlewaresNoLogging, toWaiAppPlain)
-- Any other myriad of imports ...

main :: IO ()
main = runStderrLoggingT $
  withSqlitePool "Test.db" connCount $ \pool -> liftIO $ do
    runResourceT $
      flip runSqlPool pool $ do
        runMigration migrateAll
    app <- mkApp pool
    run 3000 app

mkApp :: ConnectionPool -> IO Application
mkApp pool = do
  app <- toWaiAppPlain $ Links pool
  return $ defaultMiddlewaresNoLogging $ corsPolicy app

corsPolicy :: WAI.Middleware
corsPolicy = cors (const $ Just corsResourcePolicy)
  where
    corsResourcePolicy =
      simpleCorsResourcePolicy
        { corsMethods = ["GET", "HEAD", "POST", "PATCH", "DELETE", "OPTION"],
          corsRequestHeaders = simpleHeaders <> ["Content-Type"]
        }

vanceism7 avatar Aug 23 '22 19:08 vanceism7

I'll attach my code which is working

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

yellowbean avatar Aug 24 '22 04:08 yellowbean