Using Relative Paths in link and script Tags Using the CouchDB Server

I am playing with CouchDB a bit this weekend and I am trying to put together a basic application written in HTML and Javascript.

I wanted to use the XMLHttpRequest object to interact with CouchDB; this meant I had to host the code using the web server that is built into CouchDB (to avoid cross domain issues in the browser). However when I first moved the code over from my normal Apache server into the CouchDB server I tried to access the code with my browser at http://localhost:5984/_utils/myapplication and none of my external CSS or Javascript files would load (at least in Firefox).

What I noticed was that since I was using relative paths in the href and src attributes (i.e. <script scr="./file.js" ...) of the link and script tags, the trailing slash on the URL was required for the files to be included properly. I figured this out because when I accessed the same code at http://localhost:5984/_utils/myapplication/, everything worked as expected.

Typically web servers add that slash automatically for you, but for some reason CouchDB does not. To get around this I wrote a quick Javascript that I placed inline, just below the head tag to look for this case and correct it. The script is below.

if(String(window.location).substring((String(window.location).length - 1), String(window.location).length) != '/') {
    window.location = String(window.location) + '/';
}

Seems odd that CouchDB does not account for this.

2 Responses to “Using Relative Paths in link and script Tags Using the CouchDB Server”

  1. Jan Says:

    Hey,

    if you don’t use `./file.js` but just `file.js` it should work as expected.

    As for your JavaScript, the calls to String() are all not really needed :)

    In addition, check out path.js* that includes a ton of helpers for paths in a couchapp**.

    * http://github.com/couchapp/couchapp/blob/master/vendor/path.js
    ** http://github.com/couchapp/couchapp

    Cheers,
    Jan

  2. jordoncm Says:

    Actually I tried including the file both ways and neither worked. I however put all my CSS and Javascript in subfolders (i.e. http://localhost:5984/_utils/myapplication/javascript/file.js), perhaps that makes a difference.

    As for your second point on the use of String() type casting; substring is not a method of the location object and causes an error if called without converting the type. The others may be not needed, I did not test those.

    Thanks for the links, I will check it out.

    I am using version 0.10.0.

Leave a Reply

{
}