現在,如果請求的路由與現有的API端點或其他靜態資產不匹配,則需要從後端返回文件(例如,index.html
)並不罕見。這在使用react-router
和browserHistory
時特別方便。Catch-all或默認路由
我有點難以理解,我可能會如何與僕人接觸。我確實不知道是否攔截404的可能是要走的路,但是那當然有時API將需要合法發行404.這是我一直在使用實驗的東西類型:
data Wombat = Wombat
{ id :: Int
, name :: String
} deriving (Eq, Show, Generic)
instance ToJSON Wombat
wombatStore :: [Wombat]
wombatStore =
[ Wombat 0 "Gertrude"
, Wombat 1 "Horace"
, Wombat 2 "Maisie"
, Wombat 3 "Julius"
]
wombats :: Handler [Wombat]
wombats = return wombatStore
wombat :: Int -> Handler Wombat
wombat wid = do
case find (\w -> Main.id w == wid) wombatStore of
Just x -> return x
Nothing -> throwE err404
type API =
"api" :> "wombats" :> Get '[JSON] [Wombat] :<|>
"api" :> "wombats" :> Capture "id" Int :> Get '[JSON] Wombat :<|>
Raw
api :: Proxy API
api = Proxy
server :: Server API
server = wombats
:<|> wombat
:<|> serveDirectory "static"
app :: Application
app = serve api server
main :: IO()
main = run 3000 app
我會喜歡看一個如何添加'默認路由'的示例,以便在請求不匹配API端點或靜態目錄中的任何內容時發送HTML響應。玩具回購here。
非常感謝,這真的很有幫助! –