2010-11-01 79 views
19

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

这制作的外壳:

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

但这Node.js的代码没有工作:

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

它给了我这个数据传回:

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

如何如何使用Node.js列出所有数据库?

回答

18

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

你有两个选择:

1.构造HTTP基本授权头自己

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 LIB如one for node written in C,或者纯JS之一(例如the one that CouchDB Futon uses )。

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

一个更多的其他功能HTTP客户端,就像Restler,将使它更容易做到上述要求,包括凭据:

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

此外,如果您以编程方式调用此函数,则应该创建一个API密钥。并将该密钥权限授予数据库。数据库 - >文档(Pull-Down) - >权限。添加你的密钥,并给它'读者/作家/等等''访问。 https://my_company.cloudant.com/dashboard.html#/database/my-database/permissions – 2014-09-09 03:33:03

7

Node.js有很多CouchDB模块。

+1

node-couchdb update:不再有效/可维护的项目。 – panchicore 2011-09-15 14:07:02

+1

摇篮+1,看起来不错。 – panchicore 2011-09-15 14:11:53

+1

node-couchdb重新更新:现在维护和活动已提交2012年5月12日显示 – pulkitsinghal 2012-06-08 18:47:21

5

只想添加

  • nano - 为node.js的

到列表简约CouchDB的驱动程序。它由Nuno Job,CCO nodejitsu编写,并积极维护。

0

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

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

//Specify your Cloudant Database Connection URL. For Bluemix format is: https://username:[email protected] 

dbCredentials_url = "https://username:[email protected]"; // 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(', ')) });