没别的缘由,就是想做一个笔记,方面以后参考使用!
需求:web后端我想用c语言来实现。(linux版的已在前面的博文中提到过了)。
一、下载window版的httpd。
下载就完了。
二、修改配置并启动httpd.
将下载的.zip解压后放到文件夹中,如:D:apache下。
修改D:apacheApache24confhttpd.conf,Define SRVROOT 改为 Define SRVROOT "D:apacheApache24"。
打开cmd,cd 到D:apacheApache24in,输入httpd.exe,如果出现光标在闪,无任何消息的话,证明服务启动成功呢,不要关闭此窗口,打开浏览器,输入:http://localhost,会看到俺怕车的测试页面。
三、新建testcgi.html并保存到D:apacheApache24htdocs下,添加以下内容:
<html> <head> <script type="text/javascript" src="js/jquery.min.js"></script> </head> <body> <h1>It works!hahahahhahaha~</h1> <input type="button" onclick="testcgi()" value="test"/> </body> <script type = "text/javaScript"> function testcgi(){ $.ajax({ type: 'POST', url: '../cgi-bin/test.exe', data:"hello world", dataType: "text", ContentType: "application/text; charset=utf-8", success: function (returnedData,status) { if(status=="success"){ alert(returnedData); } }, error: function (msg) { alert("访问失败:"+ msg); } }); } </script> </html>
三新建test.c,添加以下内容,我是借助vs2015编译成test.exe程序,并放到D:apacheApache24cgi-bin下。
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #define MAXLEN 1024 char* getcgidata(FILE* fp, char* requestmethod); int main(void) { char * cgistr = NULL; char * req_method = NULL; printf( "Content-type: application/text;charset=utf-8 " ); req_method = getenv("REQUEST_METHOD"); cgistr = getcgidata(stdin, req_method); fprintf(stdout,"you post param is %s",cgistr); } char* getcgidata(FILE* fp, char* requestmethod) { char* input; int len; int size = MAXLEN; int i = 0; if (!strcmp(requestmethod, "GET")) { input = getenv("QUERY_STRING"); return input; } else if (!strcmp(requestmethod, "POST")) { len = atoi(getenv("CONTENT_LENGTH")); input = (char*)malloc(sizeof(char)*(size + 1)); if (len == 0) { input[0] = '