将 headers 添加到 c# HTTP 服务器

Adding headers to c# HTTP server

我正在尝试使用 "Simple HTTP server in c#" - (http://www.codeproject.com/Articles/137979/Simple-HTTP-Server-in-C) 在 c# 中创建一个 HTTP 服务器(侦听器),并使用 javascript.[=15 向其发送请求=]

代码如下所示:

The HandleRequest function in c#:
public override void handleGETRequest(HttpProcessor p)
        {
            p.httpHeaders.Add("Access-Control-Allow-Origin", "*");

            if (p.http_url.Equals("/test"))
            {
                p.outputStream.Write("Test accomplished");
                Console.Log("Server responded to TEST request successfully");
                return;
            }
            if (p.http_url.StartsWith("/goto"))
            {
                string[] args = p.http_url.Split('/');
                //x - [2]
                //y - [3]
                //z - [4]
                //f - [5]
                myPrinter.SendCommand(string.Format("G1X{0}Y{1}F10000", args[2], args[3]));
                p.outputStream.Write("response succeeded");
                Console.Log("goto command was executed");
            }
            if (p.http_url.StartsWith("/commandlist"))
            {
                string[] args = p.http_url.Split('/');
                //[2] - commands
                string[] commands = args[2].Split('$');
                for (int i = 0; i < commands.Length; i++)
                {
                    myPrinter.commands.Add(commands[i]);
                }
                //myPrinter.HandleCommandList();
                p.outputStream.Write("response succeeded");
                Console.Log("goto command was executed");
            }
            if (p.http_url.StartsWith("/execute"))
            {
                p.outputStream.Write("Executing " + myPrinter.commands.Count + " commands\n");
                myPrinter.HandleCommandList();
            }
        }

用JS发送的请求是这样的:

function sendGCODE() {
    var xmlhttp = new XMLHttpRequest();
    var url = "http://localhost:1300/commandlist/" + document.getElementById("Text1").value;

    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            var myArr = xmlhttp.responseText;
            myFunction(myArr);
        }
    };

    xmlhttp.open("GET", url, true);
    xmlhttp.send();

    function myFunction(arr) {
        alert('Response received');
        document.getElementById("resultP").innerHTML = arr;
    }
}

但是当我尝试从 JS 代码发送请求时,它只是告诉我缺少 "Access-Control-Allow-Origin" header,因此无法发送请求。我在 handleGETRequest() 函数的开头添加了 header,如下所示:

public override void handleGETRequest(HttpProcessor p)
        {
            p.httpHeaders.Add("Access-Control-Allow-Origin", "*");

那么为什么它不起作用?服务端软件没有报错,但是JS代码仍然因为缺少header.

而心烦意乱

我做错了什么?谢谢! (其余服务器端代码在上面的link)

我认为您应该为您的服务器启用 CORS 以接受这些请求,看看这个 guide ,也许它会有所帮助。