Simple solution for local Cross Origin Requests

If you’re working on a little front-end project and want to test it locally, you’d typically open it by pointing your local directory in the web browser, for instance entering file:///home/erick/mysuperproject/index.html in your URL bar. However, if your site is trying to load resources, even if they’re placed in your local directory, you might see warnings like this:

XMLHttpRequest cannot load  file:///home/erick/mysuperproject/mylibrary.js. Cross origin requests are only supported for HTTP. 

Chrome and other modern browsers have implemented security restrictions for Cross Origin Requests, which means that you cannot load anything through  file:/// , you need to use http:// protocol at all times, even locally -due Same Origin policies. Simple as that, you’d need to mount a webserver to run your project there.

This is not the end of the world and there are many solutions out there, including the good old Apache (with VirtualHosts if you’re running several other projects), node.js with  express, a Ruby server, etc. or simply modifying your browser settings.

However there’s a simpler and lightweight solution for the lazy ones. You can use Python’s SimpleHTTPServer. It comes already bundled with python so you don’t need to install or configure anything at all!

So cd to your project directory, for instance

and then simply use

And that’s it, you’ll see this message in your terminal

So now you can go back to your browser and visit http://0.0.0.0:8000 with all your directory files served there. You can configure the port and other things, just see the documentation. But this simply trick works for me when I’m in a rush to test a new library or work out a new idea.

There you go, happy coding!

  • Kapil Adatiya

    You made a mistake in above section. After server starts you should log on to http://localhost:8000 rather than http://0.0.0.0/8000

  • http://www.odiseo.net/ odiseo42

    0.0.0.0 is the default IP address for SimpleHTTPServer, so that’s fine enough for a quick dev session. I think that if you spend more time configuring an IP or port, you lose the convenience of such a quick service ;)

  • Dharmi

    just what I was looking to test my D3 code…thx

  • Ivan G

    A different and fantastic approach is to avoid the use of http server and use script tags with id’s for those needed external scripts, as shown at http://stackoverflow.com/questions/19847252/cross-origin-requests-are-only-supported-for-http