我正在构建一个JavaScript库,可以使用AJAX与简单的Python Web服务器通信。
以下是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");