用Node.js连接到Cloudant CouchDB?

我正尝试使用Node.js连接到Cloudant上的CouchDB数据库。

这工作在shell上:

curl https://weng:password@weng.cloudant.com/my_app/_all_docs 

但是这个node.js代码不起作用:

  var couchdb = http.createClient(443, 'weng:password@weng.cloudant.com', 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); }); }); 

它给了我这个数据:

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

我该如何做,用Node.js列出所有的数据库?

内置的Node.js http客户端是相当低级别的,它不支持HTTP Basicauthentication。 http.createClient的第二个参数只是一个主机名。 它并不期望那里的凭据。

你有两个select:

1.自己构buildHTTP基本授权标头

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

你需要一个Base64库,比如一个用C语言写的节点 ,或者一个纯JS(比如CouchDB Futon使用的那个 )。

2.使用更高级别的Node.js HTTP客户端

像Restler这样的function更强大的HTTP客户端,可以使上面的请求变得更容易,包括凭证:

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

Node.js有很多CouchDB模块。

  • node-couch – 一个CouchDB连接器
  • node-couchdb – 一个完整的API实现
  • node-couchdb-min – 具有较低抽象级别和连接池的轻量级客户机。
  • 摇篮 – 高级caching,CouchDB客户端

只是想补充

  • 纳米简约的couchdb驱动node.js

到名单。 它是由nodejitsu的 CCO Nuno Job写的,并且积极维护。

这个答案看起来有点过时了。 以下是使用以下支持Cloudant的NPM节点客户端库进行validation的更新答案。 https://www.npmjs.com/package/cloudant#getting-started

并回答他如何列出他的数据库的问题使用下面的代码。

 //Specify your Cloudant Database Connection URL. For Bluemix format is: https://username:password@xxxxxxxxx-bluemix.cloudant.com dbCredentials_url = "https://username:password@xxxxxxxxx-bluemix.cloudant.com"; // Set this to your own account // Initialize the library with my account. // Load the Cloudant library. cloudant = require('cloudant')(dbCredentials_url); // List the Cloudant databases cloudant.db.list(function(err, allDbs) { console.log('All my databases: %s', allDbs.join(', ')) });