Connect to Cloudant CouchDB with Node.js?

前端 未结 4 903
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-14 08:57

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

This worked on the shell:

    curl https://weng:password@weng.cloudant.com/m         


        
4条回答
  •  天命终不由人
    2020-12-14 09:15

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

提交回复
热议问题