Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell Scotty and Elm Http NetworkError

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

like image 875
Harold Fincher Avatar asked Jun 05 '18 18:06

Harold Fincher


1 Answers

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)
like image 185
Chad Gilbert Avatar answered Oct 19 '22 14:10

Chad Gilbert