Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send JSON between Elm Client and Haskell (Yesod) server

I'm trying to get basic JSON communication from client to server going, with the following Elm code:

import open Http

result res = case res of
    Success a -> a
    Waiting -> "Waiting"
    Failure n a-> "Failure " ++ (show n) ++ " " ++ (show a)


main =   lift asText <| lift (show . result) <|  send <| constant  <| post "http://localhost:3000" "{foo : true}"

The server is exactly as shown in this part of the Yesod book.

However, when I run the request, I get the output

"\"Failure 0 []\""

Does anybody know what I have to do to get an Elm client properly communicating with a Yesod server? I've tried a Python client, and the requests work just fine. Likewise, there are several examples on the Yesod site with successful Http requests, so I'm confident both libraries are working properly, but that I'm using them wrong.

UPDATE: The problem is client-side. I was able to get it working with chrome with security options disabled, and no changes to Yesod. I'll look for a workaround, but this is at least enough to let my development continue.

like image 902
jmite Avatar asked Sep 06 '13 01:09

jmite


2 Answers

This is caused by a cross-site scripting security feature on some sites. It was recently brought up on the Elm mailing lists (by me). There is not currently a workaround if you are committed to using your specific server, although I've had luck hosting the files on elm-server, which hosts all files in the directory you run it in.

You should check the javascript console and you'll see something like XMLHttpRequest cannot load http://www.google.com/. Origin http://localhost:8000 is not allowed by Access-Control-Allow-Origin.. If you don't, then this is a completely new issue. But I doubt that.

like image 108
mgold Avatar answered Nov 17 '22 17:11

mgold


I guess your server needs to send CORS-headers, discussed in example in this SO post: Allowing cross-origin requests in Yesod

More information about CORS in MDN and Wikipedia

Please note that the browser thinks your are doing Cross-Origin requests if

  • the domain name differs, in example you try to fetch data from foobar.com and in your browsers location you have barfoo.com
  • the subdomain is different, in example your application lives in foobar.com and you try to fetch data from api.foobar.com
  • the ports differ, in example your browser application is in localhost:8000 and you try to fetch data from localhost:8001
like image 37
NiklasN Avatar answered Nov 17 '22 17:11

NiklasN