Origin


Resu, North Garo Hills, Meghalaya 794108

Tuesday, 21 October 2014

Simple AngularJS $http request to fetch a CouchDB document

We begin first by installing CouchDB:

#yum install couchdb

After installation, we start the CouchDB server:

#service couchdb start

To see if it is running, type

#curl http://127.0.0.1:5984/ in the console, or type

http://127.0.0.1:5984/

in the browser's address bar. Either way, if all is good, you should get the JSON response:

{"couchdb":"Welcome","uuid":"a8e76df6219160824c631647aa7d9f1c","version":"1.6.1","vendor":{"version":"1.6.1","name":"The Apache Software Foundation"}}

I will skip all the curl -X CRUD operations here (you can refer it anywhere later) and we will create an example database and a document manually.

Go to http://127.0.0.1:5984/_utils/ in your browser. This is your FUTON, CouchDB's interface.

Click on "+ Create Database ... " button located at the top left corner of your Futon interface. Let us call it mars. Inside our newly created database, is another sub-interface. We click on the "+ New Document" button to create one, and the first field you see is the _id field with a 32-character hexadecimal string value, something like, 7df239fb136c51dffebf364d14000878. This is the UUID. Here, I will replace the string with satellite.


Now let us add on more field: click the "+ Add Field" button. We give the field name name and its value phobos. Save the document by clicking the "Save Document" button.

Upon clicking on the "Source" tab, you will see a structured JSON document like this:


{
   "_id": "satellite",
   "_rev": "1-70b8ebd5210674e1c3a381f0143a1d53",
   "name": "phobos"
}

We now have a JSON data in CouchDB, let us try to fetch it from inside an AngularJS controller using the $http service.

 var url = 'http://127.0.0.1:5984/mars/satellite';

 $http.get(url)
    .success(function (data, status, headers, config) {

    angular.forEach(data, function(value, key) {
$log.log(key);
$log.log(value);

    });
    }).
    error(function(data, status, headers, config) {
      // log error
    });

The console response you will get is the following:

XMLHttpRequest cannot load http://127.0.0.1:5984/mars/satellite. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.

This is because we have not set the [httpd] and the [cors] sections of our CouchDB server's local.ini file. Navigate to it

#cd /etc/couchdb

and open the local.ini file

#gedit local.ini

In the [httpd] section, append

enable_cors = true

and add another section

[cors]
origins = *
credentials = true
origins = http://localhost, https://localhost
methods = GET, POST, PUT, DELETE
headers = Authorization, Cookie


(you can do without the origins, methods, headers also for now)

Save, and restart the server

#service couchdb restart

Now you'll have your JSON data!