【问题标题】:Haskell Scotty and Elm Http NetworkErrorHaskell Scotty 和 Elm Http NetworkError
【发布时间】:2018-11-15 07:22:48
【问题描述】:

我想研究使用 haskell 作为后端和 elm 作为前端的 Web 开发。所以我写了这两个简单的“hello world”代码代码sn-ps

榆树:

import Html exposing (..)
import Html.Events exposing (..)
import Http
import Json.Decode as Decode

main : Program Never Model Msg
main = Html.program
  { view = view
  , update = update
  , init = ("default", Cmd.none)
  , subscriptions = \_ -> Sub.none }

type alias Model = String

type Msg = Get | Response (Result Http.Error String)

update : Msg -> Model -> (Model, Cmd Msg)
update msg model = case msg of
  Get -> (model, get)
  Response (Ok s) -> (s, Cmd.none)
  Response (Err e) -> (toString e, Cmd.none)


view : Model -> Html Msg
view model = div []
  [button [onClick (Get)] [text "click me"],
   text model]


get : Cmd Msg
get =  let url = "http://localhost:3000/get"
       in Http.send Response (Http.get url Decode.string)

haskell/scotty:

import Web.Scotty

main = scotty 3000 $ get "/get" $ json ("hello world" :: String)

两者都可以完美地独立工作 - 这意味着 elm 代码可以从 httpbin 等服务器获取数据,而 scotty 服务器可以处理我使用浏览器或 wget/curl 等工具发送的请求,但是当我尝试将两者一起使用时elm 中的 http.send 调用返回网络错误

我怀疑两台服务器都托管在同一台计算机上可能是一个问题(不知道为什么,但我想消除这种可能性)所以我将客户端站点托管在另一台我知道有工作连接的计算机上托管 spock 后端的计算机(与 wget 等一起使用)但它仍然无法正常工作。

我是否遗漏了一些明显的东西,或者是什么问题? 提前谢谢

【问题讨论】:

  • 您是否看到浏览器控制台中记录了任何错误?您是否从同一个端口(localhost:3000)提供 Elm 代码?
  • 没有它在不同的端口上提供服务,但实际上控制台中有一条错误消息(甚至没有看到那里:D)backup.elm:1 无法加载localhost:3000/get:否请求的资源上存在“Access-Control-Allow-Origin”标头。因此,不允许访问 Origin 'localhost:8000'。
  • 这些错误通常是由于跨域请求共享 (CORS) 限制造成的。您可能需要修改服务器以允许跨域请求。 Here is an example using wai-cors
  • 谢谢,解决了!

标签: haskell httprequest elm web-development-server scotty


【解决方案1】:

听起来您的问题是由于跨域请求共享 (CORS) 限制造成的。您可以使用 wai-cors 设置您的 CORS 政策。

例子:

import Web.Scotty
import Network.Wai.Middleware.Cors

main = scotty 3000 $ do
    middleware simpleCors
    get "/get" $ json ("hello world" :: String)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-11
    • 2015-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-29
    相关资源
    最近更新 更多