Skip to content

Instantly share code, notes, and snippets.

@gpaciga
Forked from acdha/simple_cors_server.py
Last active May 17, 2024 05:39
Show Gist options
  • Save gpaciga/2099b13ea21dcdd5a849b5e41ef2c17d to your computer and use it in GitHub Desktop.
Save gpaciga/2099b13ea21dcdd5a849b5e41ef2c17d to your computer and use it in GitHub Desktop.
Python 3: serve the current directory as HTTP while setting CORS headers for XHR debugging
#!/usr/bin/env python3
# encoding: utf-8
"""Use instead of `python3 -m http.server` when you need CORS"""
import sys
from http.server import HTTPServer, SimpleHTTPRequestHandler
class CORSRequestHandler(SimpleHTTPRequestHandler):
def end_headers(self):
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Access-Control-Allow-Methods', 'GET, OPTIONS')
self.send_header('Cache-Control', 'no-store, no-cache, must-revalidate')
return super(CORSRequestHandler, self).end_headers()
def do_OPTIONS(self):
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Access-Control-Allow-Methods', 'GET, OPTIONS')
self.send_header('Cache-Control', 'no-store, no-cache, must-revalidate')
return super(CORSRequestHandler, self).end_headers()
port = int(sys.argv[1]) if len(sys.argv) > 0 and sys.argv[1] else 8080
print(f'starting server on port {port}')
httpd = HTTPServer(('localhost', port), CORSRequestHandler)
httpd.serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment