parse json POST body

936 views Asked by At

When using the following module definition

defmodule Router.Folder do
  use Maru.Router

  namespace :folder do
    route_param :id do
      get do
        IO.puts "ID: " <> params[:id]
        json(conn, %{ user: params[:id], msg: "Hello Elixir World!" })
      end

      params do
        requires :name, type: String
      end

      post do
        IO.puts params[:name]
        IO.puts params[:token]
        IO.puts params[:id]
        IO.puts "Posting"
        json(conn, %{ msg: "Hello Elixir World!" })
        #conn |> text("Hello")
      end

    end  # end route_param :id
  end  # end namespace :folder
end  # end defmodule Router.Folder

defmodule FolderService.API do
  use Maru.Router

  before do
    plug Plug.Logger
    plug Plug.Parsers,
      pass: ["*/*"],
      json_decoder: Poison,
      parsers: [:urlencoded, :json]
  end

  mount Router.Folder
end

I get this error

** (exit) an exception was raised:
** (Maru.Exceptions.InvalidFormat) Parsing Param Error: name
(folder) lib/folder.ex:29: anonymous fn/1 in FolderService.API.route/2
(maru) lib/maru/runtime.ex:25: Maru.Runtime.parse_params/3
(folder) lib/folder.ex:29: anonymous fn/1 in FolderService.API.route/2
(folder) lib/folder.ex:29: anonymous fn/1 in FolderService.API.error_handler/1
(folder) lib/folder.ex:29: anonymous fn/1 in FolderService.API.call/2
(folder) lib/folder.ex:29: anonymous fn/1 in FolderService.API.error_handler/1
(plug) lib/plug/adapters/cowboy/handler.ex:15: Plug.Adapters.Cowboy.Handler.upgrade/4
(cowboy) src/cowboy_protocol.erl:442: :cowboy_protocol.execute/4

When running this curl command:

curl -X POST -H "Content-Type: applicaton/json" -d '{"name": "foobar"}' 'http://localhost:9000/folder/1233'

the code works fine, but if I curl

curl -X POST -d "name=foobar" 'http://localhost:9000/folder/1233'
1

There are 1 answers

0
Nice-Guy On

Everything about the module looks good. The problem is that when attempting to send a POST request with curl as you have above you need to use colons where you used =.

This should work: curl -X POST -d "name:foobar" 'http://localhost:9000/folder/1233'

Example for sending POST data.

How to POST JSON data with Curl from Terminal/Commandline to Test Spring REST?