c++ - 为什么不使用 Apache 在 CGI 中创建文件?

标签 c++ ajax apache file cgi

我想使用 CGI 和 Apache 将一些内容写入文件。

我的 HTML 文件:

使用 Ajax HTTP 方法调用 CGI 脚本。我没有向 CGI 传递任何参数。最后,我将响应文本打印到一个 div。

<!DOCTYPE html>
<html>
<head>

<script>

var xhttp;

function loadDoc() {

    try{

          xhttp = new XMLHttpRequest();

          xhttp.onreadystatechange = function() {

                if (this.readyState == 4 && this.status == 200) {
                     document.getElementById("message").innerHTML = this.responseText;
                }
          };

          xhttp.open("POST","mycgi.cgi",true);
          xhttp.send();


    }catch (exception){

            alert("Request failed: " + exception.message);
        }
}

</script>

</head>


<body>

<h2>sample ajax</h2>

<button type="button" onclick="loadDoc()">Change Content</button>

<div id ="message" />

</body>
</html>

cgi.cpp文件

这里我创建了一个写入模式的文件,将一些内容写入该文件并成功关闭。将响应文本“成功写入”发送回 HTML。

    #include <unistd.h>
    #include <iostream>
    #include <vector>
    #include <string>

    #include "cgicc/Cgicc.h"
    #include "cgicc/HTTPHTMLHeader.h"
    #include "cgicc/HTMLClasses.h"

    #include <stdio.h>
    #include <string.h>
    #include <fstream>

    using namespace std;
    using namespace cgicc;

    int main(int argc, char **argv)
    {

    Cgicc cgi;    

       try {

        ofstream myfile;
        myfile.open ("Newcgi.txt",ios::out);
        cout<<"Content-Type: text/html\n\n";
        myfile << "Writing this to a file.\n";
        cout<<"Sucessfully write";
        myfile.close();

       }
       catch(exception& e) {

       }

     return 0;

    }

但我看不到在 /var/apache2/var/www/html 中创建的任何文件。为什么会这样?应该在哪里创建一个新文件?它在 Apache 目录中吗?

任何代码问题?我也在用写入模式写入文件。我认为代码工作正常。有什么建议 ?

最佳答案

之前的评论总结:

  • 检查您的 CGI 文件的权限。通常有一个特殊的用户 nobody 拥有 /var/www 并且 Apache 使用它来执行脚本/进程。
  • 检查 C++ CGI 进程是否被 Apache 命中,它是否通过 HTTP 返回响应。
  • 检查 ofstream::is_open() 返回的内容,它试图在其中创建文件。 /tmpcgi-bin 工作目录(在 httpd.conf 中配置)是存储 CGI 进程创建的文件的最佳选择,通常它是 /var/www/cgi-bin/

关于c++ - 为什么不使用 Apache 在 CGI 中创建文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40126045/

相关文章:

php - 使用 jQuery 的动态链式选择框

javascript - 如何解决未捕获的类型错误: Illegal invocation jquery ajax

php - MAMP Pro - Apache 无法启动

apache - JMeter - 服务器之间的响应不同(200 而不是 OK)

c# - 如何使用 C# 拦截 Win32 API 调用?

c++ - 为什么在Boost中不使用Execute-Around Idiom作为用于线程安全访问对象的智能指针?

c++ - 如何在MFC中的每个CPropertyPage上OnInitDialog?

c++ - 是否还可以自定义STL vector 的 "reference"类型?

javascript - Rails 每次点击创建多个购物车记录

apache - 在Web服务器上使用随机文件夹名称来限制对其的访问-不好的主意吗?