Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connect to Cloudant CouchDB with Node.js?

I am trying to connect to my CouchDB database on Cloudant using Node.js.

This worked on the shell:

    curl https://weng:[email protected]/my_app/_all_docs

But this node.js code didn't work:

    var couchdb = http.createClient(443, 'weng:[email protected]', true);
    var request = couchdb.request('GET', '/my_app/_all_docs', {
        'Host': 'weng.cloudant.com'
    });
    request.end();
    request.on('response', function (response) {
        response.on('data', function (data) {
            util.print(data);
        });
    });

It gave me this data back:

    {"error":"unauthorized","reason":"_reader access is required for this request"}

How do I do to list all my databases with Node.js?

like image 752
ajsie Avatar asked Nov 01 '10 15:11

ajsie


3 Answers

The built-in Node.js http client is pretty low level, it doesn't support HTTP Basic auth out of the box. The second argument to http.createClient is just a hostname. It doesn't expect credentials in there.

You have two options:

1. Construct the HTTP Basic Authorization header yourself

var Base64 = require('Base64');
var couchdb = http.createClient(443, 'weng.cloudant.com', true);
var request = couchdb.request('GET', '/my_app/_all_docs', {
    'Host': 'weng.cloudant.com',
    'Authorization': 'Basic ' + Base64.encode('weng:password')
});
request.end();
request.on('response', function (response) {
    response.on('data', function (data) {
        util.print(data);
    });
});

You will need a Base64 lib such as one for node written in C, or a pure-JS one (e.g. the one that CouchDB Futon uses).

2. Use a more high-level Node.js HTTP client

A more featureful HTTP client, like Restler, will make it much easier to do the request above, including credentials:

var restler = require('restler');
restler.get('https://weng.cloudant.com:443/my_app/_all_docs', {
    username: 'weng',
    password: 'password'
}).on('complete', function (data) {
    util.print(data);
});
like image 104
Steadicat Avatar answered Oct 14 '22 23:10

Steadicat


There are lots of CouchDB modules for Node.js.

  • node-couch - a CouchDB connector
  • node-couchdb - A full API implementation
  • node-couchdb-min - Light-weight client with low level of abstraction and connection pooling.
  • cradle - a high-level, caching, CouchDB client
like image 7
Baggz Avatar answered Oct 14 '22 22:10

Baggz


Just wanted to add

  • nano - minimalistic couchdb driver for node.js

to the list. It is written by Nuno Job, CCO of nodejitsu, and actively maintained.

like image 5
zemirco Avatar answered Oct 14 '22 21:10

zemirco