Acess a servant server with a reflex-dom client

后端 未结 1 1418
一生所求
一生所求 2021-01-15 06:09

I\'m using version 0.4 of reflex-dom and I have a tiny reflex-dom client:

{-# LANGUAGE OverloadedStrings #-}
import Reflex.Dom
import qualified Data.Text as         


        
相关标签:
1条回答
  • 2021-01-15 06:46

    You probably are seeing Cross-Origin Resource Sharing (CORS) problems. You can verify this (in chrome at least) by checking your browser console for an error that looks like this:

    XMLHttpRequest cannot load http://localhost:8080/name/3. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access.

    If this is the case, you can enable CORS in your server by replacing this line :

    app = serve userAPI server
    

    with this line:

    app = simpleCors (serve userAPI server)
    

    You will need to import wai-cors:

    import Network.Wai.Middleware.Cors
    

    here is your servant server with these changes:

    {-# LANGUAGE OverloadedStrings #-}
    {-# LANGUAGE DataKinds #-}
    {-# LANGUAGE TypeOperators #-}
    
    import Servant
    import Servant.API
    import Servant.Server
    import Network.Wai
    import Network.Wai.Handler.Warp
    import Network.Wai.Logger       (withStdoutLogger)
    import Network.Wai.Middleware.Cors
    import qualified Data.Text as T
    
    main :: IO ()
    main = withStdoutLogger $ \aplogger -> do
             let settings = setPort 8080 $ setLogger aplogger defaultSettings
             runSettings settings app
    
    app :: Application
    app = simpleCors (serve userAPI server)
    
    userAPI :: Proxy API    -- API usage:  http://localhost:8080/name/2
    userAPI = Proxy
    
    type API = "name" :> Capture "pid" Int :> Get '[PlainText] T.Text
    
    server :: Server API
    server =  name
    
    name :: Monad m => Int ->  m T.Text
    name pid = return $ nameById pid
    
    nameById :: Int -> T.Text
    nameById 1 = "Isaac Newton"
    nameById 2 = "Galileo Galilei"
    nameById 3 = "Marie Curie"
    nameById _ = "UNKNOWN!!"
    
    0 讨论(0)
提交回复
热议问题