skanatek
skanatek

Reputation: 5251

Simple JSON request with cURL to Mochiweb

I have a very simple 'hello world' Mochiweb server (I just started my introduction into it), which takes a JSON request and sends it back:

'POST' ->
                case Path of
                    "dummy" ->
                        Data = Req:parse_post(),

                        Json = proplists:get_value("json", Data),

                        Struct = mochijson2:decode(Json),

                        Action_value = struct:get_value(<<"action">>, Struct),
                        Action = list_to_atom(binary_to_list(A)),

                        Result = [got_json_request, Action],

                        DataOut = mochijson2:encode(Result),
                        Req:ok({"application/json",[],[Result]});

The thing is that when I try to make a request to it with cURL it fails:

curl -i -H "Content-Type: application/json" -H "Accept: application/json" -X POST -d '{"action":"dummy"}' http://localhost:8080/dummy

The Mochiweb log is quite difficult to read, but as I understand the error happens at this line:

Json = proplists:get_value("json", Data)

I have put a couple of io:formats in the code and found out that both Data and Json variables are [] after I make a request with cURL.

On the other hand, when I do a very simple request with cURL:

curl -d '{"action":"dummy"}' http://localhost:8080/dummy

both Data and Json are [{"{\"action\":\"dummy\"}",[]}], but in that case the line Struct = mochijson2:decode(Json) fails.

For some strange reason Mochiweb does not see the JSON data in the POST request in case the header has the "application/json" value.

So, the question is: How do I make a correct POST request with JSON data to a Mochiweb server?

EDIT: Json variable has the undefined value.

Upvotes: 0

Views: 2891

Answers (2)

allenhwkim
allenhwkim

Reputation: 27738

This is not about POST nor get. It's about how you post your data to send to your server

When you send a json data to server, you need to make it as key=value

 curl -d "key=value" "http://your.domain.com/path"

Therefore, if you want to post json as '{"action":"dummy"}', for GET request

 curl -d "json='{\"action\":\"dummy\"}'" http://localhost:8080/dummy

For POST request as a file,

curl -F "[email protected]" http://localhost:8080/dummy

of course, when you send as a file, you need to read the posted file from the server side.

Upvotes: 0

Tilman
Tilman

Reputation: 2005

Try something along the lines of

Data = Req:recv_body(),
Json = mochijson2:decode(Data),
...

You should at least ensure method post and the content type ahead of this.

Upvotes: 0

Related Questions