简体   繁体   中英

How to call a function written in C with axios?

I've used a microcontroller to develop the embedded web server and I'm not sure if I can download an Apache or any other server into my controller.

However, I've successfully implemented an HTTP interface and have been hosting web pages and handling & parsing the POST request data/payload at the embedded web server side.

The issue is coming when the web page contains any form type data to be submitted.

I receive the value(s) entered by the user on the web page but I'm not able to display the data properly on the web page sent by the embedded server.

That's where there's a major issue in linking C (freeRTOS) code (server side) and JS (client side).

How can a JS web client pull data from embedded web server (in freeRTOS) given that I have a successful HTTP connection established with the web page and I'm also able to host pages as mentioned above?

Currently I'm using axios but unable to figure out how to call a C function in the URL? As it's not possible to code in C without a function.

axios({
method: 'post',
url: 'getStatus.c',
data: sampleData,
headers: {'Content-Type': 'multipart/form-data' }
})
.then(function (response) {
    console.log(response);
})

You cannot directly call a function in uncompiled C source file.

axios is a client side ( JS lib ) technology. Any server side program that you want to interact with axios must implement some sort of HTTP interface.

If you must use C to achieve something like that:

  1. Implement a CGI interface in C

CGI program can as simple as something like this ( Handling POST request is bit more difficult ):

#include <stdio.h>

int main()
{
  printf("Content-type: text/html\n\n");
  printf("<html>\n");
  printf("<body>\n");
  printf("<h1>Hello there!</h1>\n");
  printf("</body>\n");
  printf("</html>\n");
  return 0;
}

You can access POST request data the following way:

len_ = getenv("CONTENT_LENGTH");
len = strtol(len_, NULL, 10);
postdata = malloc(len + 1);
if (!postdata) { /* handle error or */ exit(EXIT_FAILURE); }
fgets(postdata, len + 1, stdin);
/* work with postdata */
free(postdata);

How to retrieve form "POST" data via cgi-bin program written in C

More on CGI C programs: http://jkorpela.fi/forms/cgic.html

Consider using libcgi http://libcgi.sourceforge.net for CGI C programs.

  1. Compile the CGI program.
  2. Use Apache2 or Nginx to serve the CGI "script" in this case the compiled binary.

If using C is not a priority:

I would recommend to use a high level language which is more suitable for web development. Python / PHP / C# / Java / etc..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM