我要做的是编写自定义的 HTTPRequestHandler 。我在MyHandler中添加了 do-OPTIONS
方法,以告诉浏览器我的服务器支持CORS。这是通过发送标头 Access-Control-Allow-Origin,Access-Control-
Allow-Methods和Access-Control-Allow-Headers完成的 。另外,我在 do_GET 方法中添加了“
self.send_header(’Access-Control-Allow-Origin’,’*’)”语句。
class MyHandler(baseHTTPRequestHandler): def do_OPTIONS(self): self.send_response(200, "ok") self.send_header('Access-Control-Allow-Origin', '*') self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS') self.send_header("Access-Control-Allow-Headers", "X-Requested-With") def do_GET(self): self.send_response(200) self.send_header('Access-Control-Allow-Origin', '*') self.send_header('Content-type', 'text/html')self.end_headers()self.wfile.write("<html><body>Hello world!</body></html>") self.connection.shutdown(1)


