[英]XhrRequest with reflex/reflex-dom
I want to perform a basic Ajax request, that's all. 我想执行一个基本的Ajax请求,就是这样。
I use reflex
for the frontend and Scotty
for the backend. 我使用
reflex
作为前端,使用Scotty
作为后端。 The Firefox Web Console tells me the request was a success and I see the expected result there. Firefox Web控制台告诉我请求是成功的,我在那里看到了预期的结果。 But the website switches from
Just "default"
to Nothing
instead of Just "success!"
但该网站从
Just "default"
切换到Nothing
而不是Just "success!"
. 。
Here is a complete minimal example: 这是一个完整的最小例子:
import Reflex (holdDyn)
import Reflex.Dom (button, el, mainWidget, display)
import Reflex.Dom.Xhr (performRequestAsync, xhrRequest, decodeXhrResponse)
import Reflex.Class (tag, constant)
import Data.Default (def)
main :: IO ()
main = do
mainWidget $ el "div" $ do
buttonEvent <- button "click me"
let defaultReq = xhrRequest "GET" "mystring" def --served by Scotty
asyncEvent <- performRequestAsync (tag (constant defaultReq) buttonEvent)
buttonDyn <- holdDyn (Just "default") $ fmap decodeXhrResponse asyncEvent
display buttonDyn
and the Scotty
part: 和
Scotty
部分:
{-# LANGUAGE OverloadedStrings #-}
import Web.Scotty
import Network.Wai.Middleware.Static
main = scotty 3000 $ do
middleware $ staticPolicy (noDots >-> addBase "/mnt/b/haskell/try-reflex/hello.jsexe")
get "/" $ do
file "/mnt/b/haskell/try-reflex/hello.jsexe/index.html"
get "/mystring" $ html "success!"
Since the debug tools tell me the request was a success, I suspect the error somewhere near decodeXhrResponse
but I am a bit lost how I should proceed debugging since it just gets compiled to (unreadable) Javascript. 由于调试工具告诉我请求是成功的,我怀疑在
decodeXhrResponse
附近的错误,但我有点失去了我应该继续调试,因为它只是编译成(不可读)Javascript。
I used the try-reflex Nix script from GitHub to set up everything and compiled with ghcjs hello.hs
in the Nix environment. 我使用GitHub中的try-reflex Nix脚本来设置所有内容,并在Nix环境中使用
ghcjs hello.hs
进行编译。
Edit: Adding the output of curl
: 编辑:添加
curl
的输出:
$ curl -G http://localhost:3000/mystring
success!%
With help from #reflex-frp
on freenode I found a solution: replacing decodeXhrResponse
with _xhrResponse_body
and using Text
for the default string worked: 从帮助
#reflex-frp
freenode上我发现了一个解决方案:更换decodeXhrResponse
与_xhrResponse_body
和使用Text
的默认字符串的工作:
buttonDyn <- holdDyn (Just $ T.pack "default") $ fmap _xhrResponse_body asyncEvent
decodeXhrResponse
expects some sort of JSON and although I tried to serve JSON via Scotty at one point it still didn't work. decodeXhrResponse
期待某种JSON,虽然我曾尝试通过Scotty服务JSON,但它仍然无效。
I wrote this simplified helper function to basically retrieve a remote URL from reflex: 我写了这个简化的辅助函数来基本上从reflex中检索一个远程URL:
curlGet :: MonadWidget t m => Text -> m (Event t Text)
curlGet url = do
let req = xhrRequest "GET" url def
pb <- getPostBuild
asyncReq <- performRequestAsync (tag (constant req) pb)
pure $ fmap (fromMaybe "Unknown error" . _xhrResponse_responseText) asyncReq
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.