使用Node.js连接Cloudant CouchDB? [英] Connect to Cloudant CouchDB with Node.js?

查看:223
本文介绍了使用Node.js连接Cloudant CouchDB?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这适用于shell:

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

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

But this node.js code didn't work:

    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列出我的所有数据库?

How do I do to list all my databases with Node.js?

推荐答案

内置的Node.js http客户端非常低级,它不支持开箱即用的HTTP Basic auth。 http.createClient 的第二个参数只是一个主机名。它不会在那里期望凭证。

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.

您有两种选择:

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使用的那个)。

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。使用更高级别的Node.js HTTP客户端

更具特色的HTTP客户端,例如 Restler ,可以更轻松地完成上述请求,包括凭据:

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

这篇关于使用Node.js连接Cloudant CouchDB?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆