使用http.server将“Access-Control-Allow-Origin”标头添加到python服务器

时间:2015-02-08 15:37:55

标签: python xmlhttprequest cross-domain simplehttpserver

我收到此错误 " XMLHttpRequest无法加载http://192.168.1.5:8090/。 No' Access-Control-Allow-Origin'标头出现在请求的资源上。起源' http://192.168.1.5'因此不允许访问。"

我有一个使用以下代码运行的python服务器。

class ServerHandler(http.server.SimpleHTTPRequestHandler):

    def do_GET(self):
        logging.warning("======= GET STARTED =======")
        logging.warning(self.headers)
        http.server.SimpleHTTPRequestHandler.do_GET(self)

    def do_POST(self):
        logging.warning("======= POST STARTED =======")
        logging.warning(self.headers)
        content_length = int(self.headers['content-length'])        
        body = self.rfile.read(content_length).decode('utf-8')
        try:
            result = json.loads(body)
            # process result
            self.wfile.write(bytes('Request has been processed.','utf-8'))
        except Exception as e:
            self.wfile.write('Request has failed to process. Error: %s', e)

Handler = ServerHandler

httpd = socketserver.TCPServer(("", PORT), Handler)
print ("Serving at: http://%(interface)s:%(port)s" % dict(interface=I or "localhost", port=PORT))
httpd.serve_forever()

我的客户端正在使用javascript。这是调用服务器的代码。

var http = new XMLHttpRequest();
    var url = "http://192.168.1.5:8090";
    var params = JSON.stringify(data_to_send);
    http.open("POST", url, true);

    //Send the proper header information along with the request
    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    http.onreadystatechange = function() {//Call a function when the state changes.
        if(http.readyState == 4 && http.status == 200) {
            alert(http.responseText);
        }   
    }
    http.send(params)

我尝试将这段代码添加到服务器端代码中。虽然

没有帮助
def end_headers(self):
        self.send_my_headers()
        http.server.SimpleHTTPRequestHandler.end_headers(self)

    def send_my_headers(self):
        self.send_header("Access-Control-Allow-Origin", "*")

如何将标头添加到服务器端响应?

0 个答案:

没有答案