AJAX和Python错误-请求的资源上不存在'Access-Control-Allow-Origin'头部

3
我正在构建一个JavaScript库,可以使用AJAX与简单的Python Web服务器通信。
以下是Web服务器类代码:
class WebHandler(http.server.BaseHTTPRequestHandler):

    def parse_POST(self):
        ctype, pdict = cgi.parse_header(self.headers['content-type'])
        if ctype == 'multipart/form-data':
            postvars = cgi.parse_multipart(self.rfile, pdict)
        elif ctype == 'application/x-www-form-urlencoded':
            length = int(self.headers['content-length'])
            postvars = urllib.parse.parse_qs(self.rfile.read(length),
                                             keep_blank_values=1)
        else:
            postvars = {}
        return postvars

    def do_POST(self):
        postvars = self.parse_POST()

        print(postvars)

        # reply with JSON
        self.send_response(200)
        self.send_header("Content-type", "application/json")
        self.end_headers()
        json_response = json.dumps({'test': 42})
        self.wfile.write(bytes(json_response, "utf-8"))

以下是我使用的Javascript方法:

var send_action = function() {
    var url = "http://192.168.1.51:8000";
    var post_data = {'gorilla': 'man'};

    $.post(url, post_data, function(data) {
        alert("success");

    })
      .done(function(data) {
        alert("second success");

    })
      .fail(function() {
        alert("error");

    })
      .always(function() {
        alert("finished");
    });
};

当我运行服务器并调用JS函数时,服务器会打印{'gorilla': 'man'},但是浏览器会闪烁错误提示,然后是完成提示。在开发者日志中,我有以下内容:

XMLHttpRequest cannot load http://192.168.1.51:8000/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

当我在$.post中指定*dataType*时,会发生相同的事情:
$.post(url, post_data, function(data) {
    alert( "success" );
}, 'json')

或者

$.post(url, post_data, function(data) {
    alert( "success" );
}, 'jsonp')

服务器和浏览器会话都在同一台设备上。

解决方案

需要在self.send_header("Content-type", "application/json")之后添加额外的头文件:

self.send_header("Access-Control-Allow-Origin", "*");
self.send_header("Access-Control-Expose-Headers", "Access-Control-Allow-Origin");
self.send_header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

我应该导入什么才能继承自“http.server.BaseHTTPRequestHandler”? - Rail Suleymanov
1个回答

10

关于Access-Control-Allow-Origin,有很多相关的话题。阅读更多信息:http://en.wikipedia.org/wiki/Same_origin_policy

self.send_header("Content-type", "application/json")之后添加以下行:

self.send_header("Access-Control-Allow-Origin","*");
self.send_header("Access-Control-Expose-Headers: Access-Control-Allow-Origin");
self.send_header(("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

你有几个错别字,但这个可以用,非常感谢! - tompreston

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接