diff --git a/spec/param_parser_spec.cr b/spec/param_parser_spec.cr index 494f90b..83ff016 100644 --- a/spec/param_parser_spec.cr +++ b/spec/param_parser_spec.cr @@ -30,18 +30,33 @@ describe "ParamParser" do params.should eq({"hasan" => "cemal", "name" => "serdar", "age" => "99"}) end - it "parses request body" do - route = Route.new "POST", "/" { } + context "when content type is application/json" do + it "parses request body" do + route = Route.new "POST", "/" { } - request = HTTP::Request.new( - "POST", - "/", - body: "{\"name\": \"Serdar\"}", - headers: HTTP::Headers{"Content-Type": "application/json"}, - ) + request = HTTP::Request.new( + "POST", + "/", + body: "{\"name\": \"Serdar\"}", + headers: HTTP::Headers{"Content-Type": "application/json"}, + ) - params = Kemal::ParamParser.new(route, request).parse - params.should eq({"name": "Serdar"}) + params = Kemal::ParamParser.new(route, request).parse + params.should eq({"name": "Serdar"}) + end + + it "handles no request body" do + route = Route.new "GET", "/" { } + + request = HTTP::Request.new( + "GET", + "/", + headers: HTTP::Headers{"Content-Type": "application/json"}, + ) + + params = Kemal::ParamParser.new(route, request).parse + params.should eq({} of String => AllParamTypes) + end end context "when content type is incorrect" do diff --git a/src/kemal/param_parser.cr b/src/kemal/param_parser.cr index 4daf81e..f8d3124 100644 --- a/src/kemal/param_parser.cr +++ b/src/kemal/param_parser.cr @@ -38,7 +38,7 @@ class Kemal::ParamParser end def parse_json - return unless @request.headers["Content-Type"]? == APPLICATION_JSON + return unless @request.body && @request.headers["Content-Type"]? == APPLICATION_JSON body = @request.body as String json = JSON.parse(body) as Hash json.each do |k, v|