Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
277 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...