我正在 Elm 中构建我的第一个 Web 应用程序,我遇到了一个问题,当我向本地服务器发出 get 请求时,Elm 说它是“NetworkError”,即使浏览器控制台说它有效。
我做了一个最小的例子如下:
服务器是用 Haskell 和Scotty制作的:
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Web.Scotty
import Data.Text.Lazy (pack)
main :: IO ()
main = scotty 3000 $ get "/" $ text $ pack "a"
它所做的只是在您向 localhost:3000 发出 get 请求时以字母“a”响应。Elm 应用程序只显示响应(如果有)和错误(如果有)和一个按钮来执行获取请求:
import Http exposing (getString, send, Error)
import Html exposing (Html, text, br, button, body, program)
import Html.Events exposing (onClick)
type Msg
= DataRequest (Result Error String)
| Refresh
type alias Model =
{ response : String
, err : String
}
main : Program Never Model Msg
main = program
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
subscriptions : Model -> Sub Msg
subscriptions _ = Sub.none
init : (Model, Cmd Msg)
init = ({ response = "", err = ""} , Cmd.none)
update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
case msg of
DataRequest (Err err) -> ({ model | err = toString err}, Cmd.none)
DataRequest (Ok response) -> ({model | response = response}, Cmd.none)
Refresh -> (model, send DataRequest (getString "http://localhost:3000"))
view : Model -> Html Msg
view {response, err} =
body []
[ text <| "Response: " ++ response
, br [] []
, text <| "Error: " ++ err
, br [] []
, button [ onClick Refresh ] [ text "Send request" ]
]
这是我执行获取请求时浏览器控制台的屏幕截图。我对这些东西不太了解,但据我所知,它看起来不错。
我想要的是“响应”在其后显示字母“a”,而“错误”为空白。相反,“错误”是“网络错误”,“响应”是空白的。
我已经把这个最小的例子放在了一个 Git repo 中,以防有人愿意尝试并告诉我出了什么问题:
https://github.com/8n8/elmnetworkerror
(我知道Elm http request 有一个非常相似的问题,returns NetworkError for successful requests但还没有答案,我认为它会从一个完整的最小示例中受益。)