6
votes

I wanted to look into web development with haskell for the back-end and elm for the front-end. So i wrote this two simple "hello world" code code snippets

elm:

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)

both work perfectly on their own - meaning the elm code can get data from servers like httpbin and the scotty server handles requests i send with a browser or tools like wget/curl etc fine but when i try to use the two together the http.send call in elm returns a network error

i suspected it may be a problem that both servers are hosted on the same computer (wouldn't know why but i wanted to eliminate the possibility) so i hosted the client site on another computer which i know has a working connection to the computer which hosts the spock back-end (works with wget etc) but it still didn't work.

am i missing something obvious, or what is the problem? thx in advance

1
Do you see any errors logged in the browser console? Are you serving the Elm code from the same port (localhost:3000)?Dogbert
no its served on a different port but there actually is an error message in the console (didn't even thing about looking there :D) backup.elm:1 Failed to load localhost:3000/get: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'localhost:8000' is therefore not allowed access.Harold Fincher
These errors are often due to Cross-Origin Request Sharing (CORS) restrictions. You may need to modify your server to allow cross-origin requests. Here is an example using wai-corsChad Gilbert
thx, solved it!Harold Fincher

1 Answers

12
votes

It sounds like your problem is due to Cross-Origin Request Sharing (CORS) restrictions. You can use wai-cors to set your CORS policy.

Example:

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

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