跨域GET请求不能在jQuery中工作,使用c#后端服务器

Cross-domain GET request not working in jQuery, with a C# backend server

本文关键字:使用 后端 服务器 工作 请求 GET 不能 jQuery 跨域      更新时间:2023-09-26

我有一个独立的HTTP服务器托管在另一个域,我用它作为我的后端服务器(c#)。它创建一个TcpListener,并在连接时创建一个新线程来处理该连接。

我使用jQuery向这个服务器发送一个ajax get请求,而jQuery发送一个OPTIONS请求。经过一番研究,我将这个片段添加到我的程序中,希望它之后能够继续处理HTTP请求。(ns是NetworkStream的一个实例,来自TcpClient.GetStream())

if (req1.StartsWith("OPTIONS"))
            {
                //req1 = req1.Split(''n')[0].Substring(9);
                string headers = string.Format(
                    "HTTP/1.0 200 OK'r'n"+
               "Access-Control-Allow-Origin: *'r'n"+
               "Access-Control-Allow-Methods: *'r'n"+
               "Access-Control-Max-Age: 1728000'r'n"+
               "Access-Control-Allow-Headers: *'r'n"+
               "Connection: Keep-Alive'r'n"+
               "Content-Type: text/plain'r'n'r'n");
                ns.Write(Encoding.ASCII.GetBytes(headers), 0, Encoding.ASCII.GetBytes(headers).Length);
                ns.Close(); client.Close();  return;
            }

不幸的是,浏览器一直向服务器发送OPTIONS请求,即使服务器发送回访问控制头,应该允许它无限制地访问。

以下是其中一个请求的网络日志:http://pastebin.com/T07Whvem

有什么建议吗?javascript代码相当琐碎,但我将包含它:

//this is just a long-poll
function waitForMsg(){
    $.ajax({
        url: "http://127.0.0.1:6969/2|||ub",
        dataType: "text",
       async: true, 
       cache: true,
        timeout:50000, 
        success: function(data){ 
            addmsg("new", data); 
            setTimeout(
                'waitForMsg()', 
                1000 
            );
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            addmsg("error", textStatus + " (" + errorThrown + ")");
            setTimeout(
                'waitForMsg()', 
                "1000"); 
        },
    });
};
$(document).ready(function(){
    waitForMsg(); /* Start the inital request */
});

我不能使用现有的web服务器,因为这不是一个真正的标准的web服务器;仅仅是一个可以通过http接受指令的服务器。

谢谢!

您需要在jQuery中启用以下设置

$(document).ready(function()
{
    $.support.cors = true;
});

见:http://api.jquery.com/jQuery.support/

相关文章: