Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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)
httpd.serve_forever()
@rmuratov

This comment has been minimized.

Copy link

@rmuratov rmuratov commented Aug 21, 2018

Thanks!

@FreyGeospatial

This comment has been minimized.

Copy link

@FreyGeospatial FreyGeospatial commented Feb 2, 2020

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

@acdha

This comment has been minimized.

Copy link
Owner Author

@acdha acdha commented Feb 2, 2020

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

@luizhenriquefbb

This comment has been minimized.

Copy link

@luizhenriquefbb luizhenriquefbb commented Mar 3, 2020

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)
@Gra55h0pper

This comment has been minimized.

Copy link

@Gra55h0pper Gra55h0pper commented Jun 17, 2020

Cool!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.