Stiffstream / restinio

Cross-platform, efficient, customizable, and robust asynchronous HTTP(S)/WebSocket server C++ library with the right balance between performance and ease of use
Other
1.15k stars 93 forks source link

How to get body of post request #134

Closed noctera closed 3 years ago

noctera commented 3 years ago

I am programming a Rest Api right now and to make a post request handler

router->http_post(
        R"(/api/register/:username.:email.:password)",
        [&](auto req, auto params) {
            const auto username = restinio::cast_to<std::string>(params["username"]);
            const auto email = restinio::cast_to<std::string>(params["email"]);
            const auto password = restinio::cast_to<std::string>(params["password"]);

            registration.registerUser(username, email, password);

            init_resp(req->create_response())
                .append_header(restinio::http_field::content_type, "text/json; charset=utf-8")
                .set_body("Person Registered")
                .done();

            return restinio::request_accepted();
        });

this is my code right now. But it is only working when I'm requesting like this

http://127.0.0.1:8080/api/register/Username.Username@gmailcom.UsernamePassword

But this isn´t the way I want it. How can I manage to read the request body in my server I want to make an api call to /api/register without any parameters, but sending username, email, password in the request body

Like this DeepinScreenshot_plasmashell_20201206135650

eao197 commented 3 years ago

Hi!

Maybe this answer on Stackoverflow will be useful for you.

noctera commented 3 years ago

Thanks for your help. I solved it by getting the header out of req and parsing it into a json object

std::string body = request_t::body();

nlohmann::json jsonObj;
try
{
    jsonObj = json::parse(body);
}
catch (const std::exception &e)
{
    auto error = e.what();
    std::cerr << e.what() << std::endl;
}

std::string username = jsonObj["username"];
std::string email = jsonObj["email"];
std::string password = jsonObj["password"];