我想要执行一个基本的Ajax请求,仅此而已。
我使用reflex作为前端,Scotty用于后端。Firefox控制台告诉我请求是成功的,我看到了预期的结果。但是网站从Just "default"转向Nothing,而不是Just "success!"。
下面是一个完整的最小示例:
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 buttonDynScotty部分:
{-# 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!"因为调试工具告诉我请求是成功的,所以我怀疑这个错误接近decodeXhrResponse,但是我有点不知道该如何进行调试,因为它只是被编译成(不可读的) Javascript。
我使用来自GitHub的try反射Nix脚本来设置所有内容,并在Nix环境中使用ghcjs hello.hs进行编译。
编辑:添加curl的输出
$ curl -G http://localhost:3000/mystring
success!% 发布于 2015-05-17 18:36:08
在#reflex-frp对freenode的帮助下,我找到了一个解决方案:用_xhrResponse_body替换decodeXhrResponse,并对默认字符串使用Text有效:
buttonDyn <- holdDyn (Just $ T.pack "default") $ fmap _xhrResponse_body asyncEventdecodeXhrResponse期望有某种JSON,虽然我曾经尝试通过Scotty提供JSON,但它仍然没有工作。
发布于 2018-07-08 23:45:54
我编写了这个简化的助手函数,主要是从反射中检索远程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) asyncReqhttps://stackoverflow.com/questions/30264504
复制相似问题