Skip to content

Instantly share code, notes, and snippets.

@rririanto
Last active April 20, 2016 00:54
Show Gist options
  • Save rririanto/40ebb31a663ba3d9cb87 to your computer and use it in GitHub Desktop.
Save rririanto/40ebb31a663ba3d9cb87 to your computer and use it in GitHub Desktop.
Python SimpleHTTPRequestHandler set Access-Control-Allow-Origin header
'''
@jimmyromanticde
Note:
python 2.x Only
Problem:
Error browser log
XMLHttpRequest cannot load http://127.0.0.1:8000/visitor.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
'''
import os
import sys
import SocketServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
PORT = 8000
class HTTPRequestHandler(SimpleHTTPRequestHandler):
def end_headers(self):
self.send_header('Access-Control-Allow-Origin', '*')
SimpleHTTPRequestHandler.end_headers(self)
def server(port):
httpd = SocketServer.TCPServer(('', port), HTTPRequestHandler)
return httpd
if __name__ == "__main__":
port = PORT
httpd = server(port)
try:
print "\nserving from localhost:" + str(port)
httpd.serve_forever()
except KeyboardInterrupt:
print "\n...shutting down http server"
httpd.shutdown()
sys.exit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment