Using a (local) webserver for trying out D3

The cross-origin problem

In webfiles using Javascript, there is a security policy as part of the web application security model. Under this policy, a web browser permits scripts contained in a first web page to access data in a second web page, but only if both web pages have the same origin. If not, content is blocked, because of a cross-origin problem.

In our D3 exercise, this can lead to problems when D3 is using asynchronous data loading functions, such as d3.csv() or d3.json(). D3 will request the data using a web request through http, and thus when you have loaded the file including this request directly from your disk (e.g. by double-clicking it), the browser considers the original file to have file:///your_dir/your_file.html as its origin, but the file that D3 requests is coming from http://your_dir/your_file.csv; These two are considered different origins, thus the file cannot be loaded...

The solution: using a webserver

So to do the latter part of the exercises, you need to serve the files through http, that is by a webserver. There are several ways to achieve this:

  1. If you run these exercises at ITC, use the intranet server facilities that are available for students and staff.
    See this page on how to create access or yourself.

  2. If you have access to an existing webserver, use ftp (or other) access to upload your files, and run them all from there...
    This includes cloud services such as Google Sites, etcetera, although not all of them allow all javascript libraries to be used.

  3. (Install and) Use a local server on your laptop through the localhost loopback connection:
    • If you run Linux or Mac OSX you usually will have a local Apache webserver. Try pointing your browser to the address
      http://localhost
      and if that does not work you maybe have to start the server first by typing into the terminal:
      sudo apachectl start 
    • If you have Node installed, use its local server (see the Node pages)

    • I you already have Python on your system, you can use its local server:
      In the same directory where you have your HTML file, start the server using Python3:
      $ python -m http.server
      Serving HTTP on 0.0.0.0 port 8000 ...

      Or, for Python2:

      $ python -m SimpleHTTPServer
      Serving HTTP on 0.0.0.0 port 8000 ...

      In this message, Python tells you the IP address (0.0.0.0) and the port number (8000) it is using for its webservices. So, if your file is named d3_template.html, you can get to this page via
      http://0.0.0.0:8000/d3_template.html or http://localhost:8000/d3_template.html