AJAX和Python错误 - 请求的资源上没有“Access-Control-Allow-Origin”标头

[英]AJAX and Python Error - No 'Access-Control-Allow-Origin' header is present on the requested resource


I'm building a Javascript library that can talk to a simple Python web server using AJAX.

我正在构建一个可以使用AJAX与简单的Python Web服务器通信的Javascript库。

Here is the web server class:

这是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"))

And here is the Javascript method I'm using:

这是我正在使用的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");
    });
};

When I run the server and call the JS function the server prints {'gorilla': 'man'} but then the browser flashes the error alert followed by the finished alert. In the developer log I have:

当我运行服务器并调用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.

The same thing happens when I specify *dataType*s in $.post like so:

当我在$ .post中指定* dataType * s时会发生同样的事情:

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

or

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

Both the server and the browser session are on the same machine.

服务器和浏览器会话都在同一台计算机上。

Solution

Needed to add extra headers after self.send_header("Content-type", "application/json"):

需要在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");

1 个解决方案

#1


10  

There is a lot of topics about: Access-Control-Allow-Origin. Read more: http://en.wikipedia.org/wiki/Same_origin_policy

有很多主题:Access-Control-Allow-Origin。阅读更多:http://en.wikipedia.org/wiki/Same_origin_policy

Add this lines after: self.send_header("Content-type", "application/json")

在以下后面添加以下行: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://www.silva-art.net/blog/2014/01/15/15516c54a60cacf77a9069d3711fcdf6.html



 
© 2014-2018 ITdaan.com 粤ICP备14056181号