我正在構建一個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");
我應該怎麼導入到能夠從「http.server.BaseHTTPRequestHandler」繼承? –