Wednesday, May 23, 2012

got python? you got a webserver...

At Peter Cooper's How to Build a Chat Room in JavaScript in Under an Hour webinar I learned this trick: if you have python installed on your system (many OSX machines do by default), you have a cheap-and-cheerful, ready-to-go web content server:
Just go to the relevant directory and type:

python -m SimpleHTTPServer 8081

or whatever port you want, and you can then go to http://localhost:8081/
(Slightly longer explanation at the Linux Journal.)

This can be especially user because some browsers are a bit weird about loading stuff from the file system, you run into odd cross-site-scripting style issues, like if you try to load a static ".json" file or what not.

By the way Peter Cooper also runs Javascript Weekly, a roundup of JavaScript news and articles. Great to finally have found a way to keep up with neat stuff in the industry...

UPDATE:
There's a variant if you want to run scripts:


python -m CGIHTTPServer 8081

It's pretty old-school; you make a cgi-bin directory under where you will run the command. Your scripts then have to start with #!/usr/bin/php or whatever, and have execute permissions.

Also I just realized (duh) that PHP has its own webserver-


 php -S localhost:8000

Which avoids some pesky header issues when I was trying to run through Python CGI.

UPDATE UPDATE
I was running into CORS problems running my own dev server ("Access-Control-Allow-Origin" issues). The python based solutions I googled up looked annoying, but here's another basic webserver you can use, with an argument that runs around the CORS issues: 

npx http-server . -p 9999 --cors='*'

(Obviously pick your own port)

UPDATE UPDATE UPDATE

 
UPDATE UPDATE UPDATE UPDATE

Oddly missing from that previously linked list (tho mentioned in a comment:

npx serve@latest

No comments:

Post a Comment