当在elm-reactor
中运行以下程序(或使用elm-make
进行此操作)时,我发现它实际GET
s的唯一网页是httpbin。否则,我会看到一个http.networkerror,甚至在诸如“http://google.com”或“http://stackoverflow.com”之类的可靠站点上也是如此。我完全搞不懂这是为什么,有人能指出我的错误吗?
module Main (..) where
import Http
import Html exposing (..)
import Effects
import Html.Events as Events
import StartApp
import Task
-- MODEL
type alias Model =
{ output : String }
type Action
= Response String
| Request String
| HTTPError Http.Error
-- UPDATE
update : Action -> Model -> ( Model, Effects.Effects Action )
update act mod =
case act of
Response str ->
( { mod | output = str }, Effects.none )
Request srv ->
let
effects =
srv
|> Http.getString
|> Task.map Response
|> flip Task.onError (Task.succeed << HTTPError)
|> Effects.task
in
( { mod | output = "GET: " ++ srv }, effects )
HTTPError err ->
( { mod
| output =
"Error: "
++ case err of
Http.Timeout ->
"Timeout"
Http.UnexpectedPayload str ->
"Unexpected payload: " ++ str
Http.BadResponse code str ->
"Bad response: " ++ toString code ++ ": " ++ str
Http.NetworkError ->
"Network error"
}
, Effects.none
)
-- VIEW
view : Signal.Address Action -> Model -> Html.Html
view address mod =
div
[]
[ div
[]
[ input
[ Events.on "input" Events.targetValue (Request >> Signal.message address) ]
[]
]
, div [] [ text mod.output ]
]
-- MAIN
app : StartApp.App Model
app =
StartApp.start
{ init = ( { output = "No requests made" }, Effects.none )
, update = update
, view = view
, inputs = []
}
main =
app.html
port tasks : Signal (Task.Task Effects.Never ())
port tasks =
app.tasks
最佳答案
您很可能遇到跨源浏览器限制。当请求失败时,请查看浏览器javascript控制台。chrome会记录如下错误:
xmlhttprequest无法加载https://www.stackoverflow.com/。请求的资源上不存在“访问控制允许源”头。因此不允许访问源“http://elm-lang.org”。
工作的httpbin示例链接包含http头Access-Control-Allow-Origin: *
,这是限制性最小的设置。
您可以通过查找CORS(代表跨源http请求)上的信息,了解更多关于这些类型问题的信息以及解决这些问题的方法。