Skip to content

Instantly share code, notes, and snippets.

Last active July 11, 2024 02:36
Show Gist options
  • Save acdha/925e9ffc3d74ad59c3ea to your computer and use it in GitHub Desktop.
Save acdha/925e9ffc3d74ad59c3ea 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"""
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')
self.send_header('Cache-Control', 'no-store, no-cache, must-revalidate')
return super(CORSRequestHandler, self).end_headers()
httpd = HTTPServer(('localhost', 8003), CORSRequestHandler)
Copy link


Copy link

Saved me from experiencing several more hours of pain. Thank you!

Copy link

acdha commented Feb 2, 2020

@FreyGeospatial: glad it helped — I’ve saved myself at least once by finding this in a search result, too 😀

Copy link

it works very well, but if someone needs to pass the port number dynamically (like the original http.server), change line 16 with.

import sys
PORT = sys.argv[1]
httpd = HTTPServer(('localhost', PORT), CORSRequestHandler)

Copy link


Copy link

Saved my day, thanks!

Copy link

gigity-gigity commented Sep 14, 2022

Hey guys,

I am hosting a directory in my local system where I have some files I want to access using another domain and port in my local system. In this process, I am getting a CORS error. I am hosting the directory with some files using the node command "HTTP-server -p 8000" from the terminal. I am getting a CORS error when accessing these files from something like the "" domain. Can anyone help me host these directories with CORS access for I will be highly grateful for your help.
(I specifically want help hosting the directory with CORS access, not an HTML page. Examples of hosting an HTML page with CORS access are well documented on the web. Also, as a beginner web developer, I may be asking a dumb question, please pardon me.)

Thank You,
Prashant Upadhyay

Copy link

docjojo commented Oct 9, 2023

Great script, thank you!

Copy link

so nice, thank you ^^b

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment