0

I am trying to make a POST request with Postman to my Rust API:

#![feature(proc_macro_hygiene, decl_macro)]

#[macro_use]
extern crate rocket;
#[macro_use]
extern crate serde_derive;

use rocket_contrib::json::{Json, JsonValue};

#[derive(Serialize, Deserialize)]
struct Response {
    status: String,
}

#[get("/")]
fn index() -> &'static str {
    "Hello, world!"
}

#[post("/register", format = "json", data = "<register>")]
fn user_create(register: Json<Response>) -> Json<Response> {
    Json(Response {
        status: "works".to_string(),
    })
}

fn main() {
    rocket::ignite()
        .mount("/", routes![index, user_create])
        .launch();
}

Cargo.toml:

[package]
name = "hello-rocket"
version = "0.1.0"
authors = [""]
edition = "2018"

[dependencies]
rocket = "0.4.6"
serde = { version = "1.0", feature = ["derive"]}
serde_json = "1.0"
serde_derive = "1.0"

[dependencies.rocket_contrib]
version = "0.4.6"
default-features = false
features = ["json"]

I have configured a Content-Type: application/json header within Postman and the body of my request is {"status": "running"}:

enter image description here

I am getting

Error: Couldn't parse JSON body: Error("EOF while parsing a value", line: 1, column: 0)
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • 1
    This code seems to work for me. Double check everything: correct request (POST /register), correct host, latest build, ensure there aren't any weird bytes in your request. If that doesn't work, include your dependencies' versions and a reproducible sample (rocket `.mount`, `.launch` and all). – kmdreko Nov 15 '20 at 00:10
  • @kmdreko I updated my cargo and rustup version, and make sure all my dependencies are in their latest version. I even created a new project to test it out and it still does not work. – Svetoslav Tsenov Nov 15 '20 at 02:04
  • Add your full code and cargo.toml to your post – kmdreko Nov 15 '20 at 02:07
  • This isn't a Rust problem: `curl -X POST --header 'Content-Type: application/json' --data '{"status": "running"}' http://localhost:8000/register` ==> `{"status":"works"}`. You must be misusing postman. – Shepmaster Nov 15 '20 at 14:19
  • You also have warnings. **Always** address **all** warnings when you are trying to debug a problem! `warning: unused manifest key: dependencies.serde.feature` – Shepmaster Nov 15 '20 at 14:21
  • runnig the exact same curl command gives me 404. – Svetoslav Tsenov Nov 15 '20 at 15:35
  • Again, this code seems to work for me. If it fails with both postman and curl then something else is going on. The error you see is when the json header is set but there is no body. So either there's code you're not showing or something is stripping out the body of your request (proxy, firewall, etc). – kmdreko Nov 15 '20 at 15:47

1 Answers1

0

Set the postman headers "Content-Type" and "Content-Length":

postman headers

[ "work..." ]