I have a html form with the action set as a route on my cpp-httplib server. I am trying to get the data from the submitted form fields in a post request from my Post route and return them back to my server for processing. I am not using cpp-httplib’s client class. Only the server. I cannot get any of the form data as the params and body of the request are empty.
<form class="rate_form" id="form_0" action="/test" method="post" accept-charset="utf-8">
svr.Post("/test", [&](const Request & req, Response &res)
{
string s;
char buf[BUFSIZ];
string query;
for (auto it = req.params.begin(); it != req.params.end(); ++it) {
const auto &x = *it;
snprintf(buf, sizeof(buf), "%c%s=%s",
(it == req.params.begin()) ? '?' : '&', x.first.c_str(),
x.second.c_str());
query += buf;
}
snprintf(buf, sizeof(buf), "%sn", query.c_str());
s += buf;
printf("request params: %sn", s.c_str());
printf("request body: %sn", req.body.c_str());
printf("request method %sn", req.method.c_str());
});
When I run my server and submit the above form to the “/test” route, not only are the params, in this case the string s, empty but also req.body. I thought this might have something to do with the content-type as it is set to application/x-www-form-urlencoded
by default on form submission. When I change the content-type to "multipart/form-data"
and use a ContentReader in my route like so:
svr.Post("/test", [&](const Request &req, Response &res, const ContentReader &content_reader)
{
std::string body;
content_reader([&](const char *data, size_t data_length) {
body.append(data, data_length);
return true;
});
printf("request body: %sn", req.body.c_str());
printf("request method %sn", req.method.c_str());
res.set_content(body, "text/plain");
});
body, and req.body are empty and I am returned with a 400 code instead of a 200. I’ve tried lots of different things and have dug though piles of other examples and the httplib.h file myself without any results. I understand there is probably a simple solution but I’m just not finding it/seeing it. This is my first question here, so please let me know if anything needs clarification.
Fox Rodina is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.