This blog post has moved to blog.stvjam.es

You should be redirected shortly, alternatively please click the following link

Setting up a project to use AJAX with WebStorm

Applies to  : Webstorm IDE v5.0, AJAX
Note : Webstorm 6.0 comes with a built in web server as per Louis' comment below so this post would only apply to previous versions.

At the moment I'm getting settled into using the Webstorm IDE and so far loving it... Definitely one of the most frictionless JavaScript development experiences I've had so far.

This post addresses setting up html/javascript projects that play nicely with $.ajax , or $.get calls on your local machine using WebStorm

You might, like me, jump in there for the first time, start using it, get excited when you see all the cool features, live edit and do all sorts of awesome stuff, finally decide to use it to stick your teeth into a repo and then get surprised when you get something like this :

XMLHttpRequest cannot load file:///C:/Users/AMonkey/Code/aproject/data/data.json. Origin null is not allowed by Access-Control-Allow-Origin.

This is a pretty standard browser security message to say "Hey you can't get content (resources) from another place (origin) and pass it off using ajax in your site" [more...] , so the only mystery is why we are getting this when we are in fact working off the same site/origin.

Well thats because file:/// doesn't publish an Origin in the header, so when the browser inspects the header to see if the response is coming from the same place, it fails validation.

There are a two different solutions to this, one is to use a local web server, so that all responses come from the same origin, the other (as recommended by Basarat Ali Sayed in his helpful post) is to use WebStorm's settings with flags to tell your Chrome Browser to allow cross origin resources 

The Chrome option is nice and clean if thats the browser you're using, if you want more info on setting up a simple local server, read on.

Setting up a Simple local http server

I'd recommend downloading and installing python and using the SimpleHTTPServer module to serve up your site

C:\Users\AMonkey\Code\AProject\python -m SimpleHTTPServer

(This will start by default on port 8000)

Now in Webstorm on the Quick Start page :





There you go, now when you Preview it will run off http://localhost not file:// and all your CORS AJAX worries will be a thing of the past.

(You will of course have to fire up your python server each time you want to run your project in this way, you can always batch file it for convenience)


Labels: , , ,