[英]Connect to Cloudant CouchDB with Node.js?
我正在尝试使用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 Basic auth。 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库,例如一个用C语言编写的节点 ,或一个纯JS库(例如CouchDB Futon使用的那个 )。
2.使用更高级别的Node.js HTTP客户端
像Restler这样功能更强大的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模块。
这个答案看起来有点过时了。 以下是我使用以下Cloudant支持的NPM节点客户端库验证的更新答案。 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(', ')) });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.