Avoiding cross-origin request errors

I have recently been learning how to use the Google Maps API to visualize geo-tagged data for a project I’m involved in. Since this API works with JavaScript, this implies a lot of debugging by running the scripts from a local folder. However, this causes problems when trying to load (server-side) files using the XMLHttpRequest JavaScript class. Specifically, I’m referring to the “Cross origin requests are only supported for HTTP” error. Initially this seemed to make no sense, as the file in question was in the same folder (so definitely in the same domain) as the script HTML. However, if the HTML is loaded using a local (file:///) protocol, so will the file be, violating the security policy.

This seems to be a well-known problem. Luckily the solution is rather simple. All that’s needed is to load the script from a local web server. Rather than install and configure Apache or similar, Python quickly comes to the rescue. Running

python -m SimpleHTTPServer

will start a local web server running on port 8000, with the document root being the current working directory.

Advertisements

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s