Serve static content in a local webserver in 5 words or less

Posted by Katie McLaughlin on September 5, 2014

I've hit an issue where I want to view a copy of a website -- full of html, javascript, css, and what have you -- locally. This is fine, you can usually just go file:///home/user/project/index.html, and Bob's your uncle.

However, due to Chrome (and presumably Firefox) and their security limitations, you cannot use ajax calls locally. This means that a $.get("file.txt",function(d){}) call in that local website directory you have won't work.

There are ways around this. You could convert the text in your file.txt into a javascript object and then parse that. But I like doing things in a non-destructive way. And I found it in an old serverfault post. Simple invoke the power of python -

python -m SimpleHTTPServer PORT

Then you can have your cross-site scripting that's actually a localhost, and eat it too[0]

For Python3, use

python -m http.server PORT

The -m flag refers running a library module as a script. You can use this trick to do other cool things, like parsing pretty json to the terminal, using python -m json.tool filename

NB. This post refers to "5 words or less" because

 $echo "python -m SimpleHTTPServer PORT"  | wc -w
 4

[0] Consumption of local webservers not recommended