From b072d75300f3349d8e39067dfd25b925713e8bd7 Mon Sep 17 00:00:00 2001 From: Anas Alkhatib Date: Thu, 15 Jun 2023 07:51:35 -0400 Subject: [PATCH] http post --content-type should set Content-Type header (#9431) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Parse the data from string to json if the `--content-type "application/json"` flag is used for the request. Fixes: https://github.com/nushell/nushell/issues/9408 In the issue, the actual data is a string `'{ "query": "{ greeting }" }'` representing json, and it would match the case `Value::String { val, .. }` ------------------------- The example in the issue does set the `content-type` to `application/json` but sends the body as a string note the `'`. ``` ( ::: http post ::: -fer ::: # -H [ "Content-Type" "application/json" ] ::: --content-type "application/json" ::: 'http://127.0.0.1:3000/greetings/hello' ::: '{ "query": "{ greeting }" }' ::: ) ``` ``` ╭─────────┬───────────────────────╮ │ headers │ {record 14 fields} │ │ body │ {"content_type":null} │ │ status │ 200 │ ╰─────────┴───────────────────────╯ ``` If we send the same request but using actual json as the body, the Header is set correctly. ``` ( ::: http post ::: -fer ::: # -H [ "Content-Type" "application/json" ] ::: --content-type "application/json" ::: 'http://127.0.0.1:3000/greetings/hello' ::: { "query": "{ greeting }" } ::: ) ``` ``` ╭─────────┬─────────────────────────────────────╮ │ headers │ {record 14 fields} │ │ body │ {"content_type":"application/json"} │ │ status │ 200 │ ╰─────────┴─────────────────────────────────────╯ ``` --- crates/nu-command/src/network/http/client.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/nu-command/src/network/http/client.rs b/crates/nu-command/src/network/http/client.rs index 5f65f08b9..8d6d5e895 100644 --- a/crates/nu-command/src/network/http/client.rs +++ b/crates/nu-command/src/network/http/client.rs @@ -170,6 +170,10 @@ pub fn send_request( Box::new(move || request.send_bytes(&val)), ctrl_c, ), + Value::String { .. } if body_type == BodyType::Json => { + let data = value_to_json_value(&body)?; + send_cancellable_request(&request_url, Box::new(|| request.send_json(data)), ctrl_c) + } Value::String { val, .. } => send_cancellable_request( &request_url, Box::new(move || request.send_string(&val)),