2014-01-15 24 views
3

我正在构建一个Javascript库,可以使用AJAX与简单的Python Web服务器通信。AJAX和Python错误 - 请求的资源上没有“Access-Control-Allow-Origin”标头

这里是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'}但随后浏览器闪烁错误警报,然后完成警报。在开发者日志中我有:

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

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

无论是服务器和:

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 *就像于是同样的事情发生浏览器会话在同一台机器上。

解决方案

所需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"); 
+0

我应该怎么导入到能够从“http.server.BaseHTTPRequestHandler”继承? –

回答

10

有很多关于主题:访问控制允许来源。了解更多: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"); 
+0

你有一些错别字,但这个工作,非常感谢你! – tompreston

相关问题