void fn(struct mg_connection *c, int ev, void *ev_data, void *fn_data)
{
if (ev == MG_EV_HTTP_MSG)
{
struct mg_http_message *hm = (struct mg_http_message *) ev_data;
if (mg_http_match_uri(hm, "/api/hello")) // On /api/hello requests,
{
char html[1000];
strcpy(html, "<!DOCTYPE html>"
"<html>"
"<head>"
"</head>"
"<body>"
"<form action=\"sum\" method = \"GET\">"
"<label> Number 1</label>"
"<input type=\"text\" name=\"number1\"> <br>"
"<label> Number 2</label>"
"<input type=\"text\" name=\"number2\"><br>"
"<input type=\"submit\" value=\"Add\">"
"</form>"
"</body>"
"</html>");
mg_http_reply(c, 200, "Content-Type: text/html\r\n", html);
}
else if(mg_http_match_uri(hm, "/api/sum"))
{
struct mg_str params = hm->body;
double num1, num2;
if(mg_json_get_num(params, "$[0]", &num1) &&
mg_json_get_num(params,"$[1]", &num2))
{
mg_http_reply(c, 200, "Content-Type: text/plain\r\n", "result:%g\n", num1 num2);
}
else
{
mg_http_reply(c, 500, "NULL", "%s","Parameters Missing");
}
}
else // For all other URIs,
{
mg_http_reply(c, 200, "Content-Type: text/plain\r\n", "%s\n", "Static Content");
}
}
}
void task1(void)
{
struct mg_mgr mgr;
mg_mgr_init(&mgr); // Init manager
mg_http_listen(&mgr, "http://10.0.0.6:8000", fn, &mgr); // Setup listener
for (;;) mg_mgr_poll(&mgr, 1000); // Event loop
}
In the code main.c calls task1(). When I type the URL "http://10.0.0.6:8000/api/hello" I am getting the html form. But on submitting the form I am not able to go to "http://10.0.0.6:8000/api/sum".
Tried
else if(mg_http_match_uri(hm, "/api/sum"))
{
mg_http_reply(c, 200, "Content-Type: text/plain\r\n", "%s\n", "Static Content");
}
and is working fine. I suspect the problem is in getting parameter values. In Java we have request.getparameter() for getting required parameters, Do we have something like that in mongoose.
So please tell me the correct way to get parameter values in a URL.
CodePudding user response:
The problem is that you're submitting a form via GET, e.g. parameters are passed in the query string (in the URL). And you're getting parameters from the body.
There are two ways to fix your code.
- Submit parameters in the HTTP body. To do that, change your form's method from
GET
toPOST
. - OR, get parameters from the query string. To do that, change
struct mg_str params = hm->body;
tostruct mg_str params = hm->query;
Hope that helps.