5nd*_*ndG 4 haskell http elm scotty
我正在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"
Run Code Online (Sandbox Code Playgroud)
当你向localhost:3000发出get请求时,它所做的就是回复字母'a'.Elm应用程序只显示响应(如果有)和错误(如果有)和按钮来执行get请求:
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" ]
]
Run Code Online (Sandbox Code Playgroud)
这是我执行get请求时浏览器控制台的屏幕截图.我对这些东西并不是很了解,但就我所见,它看起来很好.

我想要的是'响应'在它之后显示字母'a',并且'错误'是空白的.相反,'错误'是'NetworkError','Response'是空白的.
我把这个最小的例子放在一个Git仓库中,以防任何人都很友好地试一试并告诉我出了什么问题:
https://github.com/8n8/elmnetworkerror
(我知道有一个非常类似的问题,在Elm http请求返回NetworkError以获得成功的请求但是还没有答案,我认为它将从一个完整的最小例子中受益.)
我不能说你的错误是什么,但由于CORS我收到错误:
Main.elm:1 Failed to load http://localhost:3000/:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:8000' is therefore not allowed access.
Run Code Online (Sandbox Code Playgroud)
所以我已经调整了你Main.{hs,elm}来自同一服务器的文件服务,因为访问正在发生:
Refresh -> (model, send DataRequest (getString "/data"))
Run Code Online (Sandbox Code Playgroud)
main = scotty 3000 $ do
get "/" $ file "../index.html"
get "/data" $ text $ pack "a"
Run Code Online (Sandbox Code Playgroud)
而不是使用elm-reactor我运行elm-make src/Main.elm --output=index.html