jQuery 'get' 没有从 FastCGI 应用程序(nginx Web 服务器)C++接收正确的答案

jQuery 'get' does not receive proper answer from C++ FastCGI application (nginx web server)

本文关键字:C++ 答案 服务器 get FastCGI nginx jQuery 应用程序 Web      更新时间:2023-10-16

我有使用fastcgi与网页交互的c++后端应用程序。网页使用jQuery的"get"方法向该应用程序发送请求,但无法收到正确的答案。所有这些都可以在nginx上工作。

这里是c++应用程序的简化源代码(它使用FastCGI c++库libcgi)。Lib from http://www.fastcgi.com/drupal/node/5)

#include <string>
#include "fcgi_stdio.h"
int main() {
    FCGX_Init();
    std::string port=":9000";
    int listenQueueBacklog = 400;
    int listen_socket = FCGX_OpenSocket(port.c_str(), listenQueueBacklog);
    FCGX_Request request;
    FCGX_InitRequest(&request, listen_socket, 0);
    while(FCGX_Accept_r(&request) == 0)
    {
         FCGX_FPrintF(request.out, "Content-type: text/htmlr nrn<TITLE>fastcgi</TITLE>n<H1>Fastcgi: Hello world.</H1>n");
         FCGX_Finish_r(&request);
    }
    return 0;
}

这是网页的来源。

<html>
    <head>
        <script type="text/javascript" src="jquery-1.7.min.js"></script>
    </head>
    <body>
        <script type="text/javascript">
            $.get("http://localhost:8081", function(data, status, xhr) {  alert("Data=" + data + ";Status=" + status); });
        </script>
    </body>
</html>

这里是nginx配置的一部分

server {
    listen       8080;
    server_name  localhost;
    location / {
        root   html;
        index  index.html index.htm;
    }
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   html;
    }
}
server {
    listen       8081;
    server_name  localhost;
    location / {
        fastcgi_pass   127.0.0.1:9000;
        include        fastcgi_params;
    }
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   html;
    }
 }

在打开网页后,我在c++应用程序中收到请求(在while循环内的断点停止)。但是在执行FCGX_Finish_r之后,我没有看到任何警报,即回调函数没有被调用。(当我使用jQuery 1.4.2而不是1.7时,回调函数被调用,但没有数据,我看到' data =;Status=success'警告窗口,所以问题仍然存在)。

还有一件事-如果我只是打开'http://localhost:8081'在浏览器中,一切都是正确的,我看到'Fastcgi:你好,世界。

如果有人能指出问题所在,我将非常感激。

更新:

我编辑了nginx配置(删除了8081的服务器侦听并添加了fastcgi pass到文件夹)

server {
    listen       8080;
    server_name  localhost;
    location / {
        root   html;
        index  index.html index.htm;
    }
    location /foo {
        fastcgi_pass   127.0.0.1:9000;
        include        fastcgi_params;
    }
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   html;
    }
}

和网页源代码

$.get("http://localhost:8080/foo", function(data, status, xhr) { alert("Data=" + data + ";Status=" + status); });

根据omnosis的建议,一切都开始正常工作!

http://localhost:8081这会导致错误,因为它从不同的URL调用,虽然这只是端口不同,所以这个请求实际上是一个跨域请求,被浏览器禁用。

你应该看看这些主题:

AJAX响应在c++中无效,但在Apache

和使用apache代理转发的解决方案,如Byron Whitlock建议的:

apache HTTPD扩展帮助

您应该将文件夹转发到端口,而不是localhost:8081,您应该使用localhost:8080/foo或其他文件,如localhost:8080/foo.cgi,或使用子域名,如foo.localhost:8080

我不知道如何配置也许这是好的