添加一个';访问控制允许原点';使用http.server指向python服务器的头
我得到了这个错误 无法加载XMLHttpRequest。请求的资源上不存在“Access Control Allow Origin”标头。因此不允许访问源“” 我有一个运行以下代码的python服务器添加一个';访问控制允许原点';使用http.server指向python服务器的头,python,xmlhttprequest,cross-domain,simplehttpserver,Python,Xmlhttprequest,Cross Domain,Simplehttpserver,我得到了这个错误 无法加载XMLHttpRequest。请求的资源上不存在“Access Control Allow Origin”标头。因此不允许访问源“” 我有一个运行以下代码的python服务器 class ServerHandler(http.server.SimpleHTTPRequestHandler): def do_GET(self): logging.warning("======= GET STARTED =======") logg
class ServerHandler(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
logging.warning("======= GET STARTED =======")
logging.warning(self.headers)
http.server.SimpleHTTPRequestHandler.do_GET(self)
def do_POST(self):
logging.warning("======= POST STARTED =======")
logging.warning(self.headers)
content_length = int(self.headers['content-length'])
body = self.rfile.read(content_length).decode('utf-8')
try:
result = json.loads(body)
# process result
self.wfile.write(bytes('Request has been processed.','utf-8'))
except Exception as e:
self.wfile.write('Request has failed to process. Error: %s', e)
Handler = ServerHandler
httpd = socketserver.TCPServer(("", PORT), Handler)
print ("Serving at: http://%(interface)s:%(port)s" % dict(interface=I or "localhost", port=PORT))
httpd.serve_forever()
我的客户端正在使用javascript。这是调用服务器的代码
var http = new XMLHttpRequest();
var url = "http://192.168.1.5:8090";
var params = JSON.stringify(data_to_send);
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params)
我尝试将这段代码添加到服务器端代码中,但没有效果
def end_headers(self):
self.send_my_headers()
http.server.SimpleHTTPRequestHandler.end_headers(self)
def send_my_headers(self):
self.send_header("Access-Control-Allow-Origin", "*")
如何将标题添加到服务器端响应?这对我来说很有效: