如何使用纯NodeJS从CouchDB Cloudant获取和显示数据?

时间:2015-11-11 00:17:14

标签: database node.js couchdb cloudant

我认为这是许多初学者的基本问题。我有同样的问题。

如何从PURE NodeJS代码轻松发送请求并获得简单的JSON?如何将数据发送到Web响应?

1 个答案:

答案 0 :(得分:3)

首先向数据库发送请求并显示到控制台:

https://nodejs.org/api/https.html

var https = require('https');

var db_options = {
    "auth": "{{name}}:{{pwd}}",
    "host": "{{name}}.cloudant.com",
    "port": "443", // or 80
    "path": "/{{db_name}}/_all_docs"
}

https.request(db_options, function(response) { // or http

    var out = '';

    response.on('data', function(data) {
        out += data;
    });

    response.on('end', function() {
        console.log(out);
    })

})
.on('error', function(err) {
    console.log(err);
})
.end();

然后根据基本示例Node.js:

将其包装到Web服务器

https://nodejs.org/api/synopsis.html

var http = require('http');

var server_ipAddr = '127.0.0.1';
var server_port = 8080;

var server_http = http.createServer(function(req, res) {

...

      response.on('end', function() {
        res.end(out); // <-- add or replace "console.log(out);"
      })

...


}).listen(server_port, server_ipAddr);

您可以单独使用这些代码。一起看起来像这样:

var http = require('http');

var server_ipAddr = '127.0.0.1';
var server_port = 8080;

var server_http = http.createServer(function(req, res) {

    var https = require('https');

    var db_options = {
        "auth": "{{name}}:{{pwd}}",
        "host": "{{name}}.cloudant.com",
        "port": "443", // or 80
        "path": "/{{db_name}}/_all_docs"
    }

    https.request(db_options, function(response) { // or http

        var out = '';

        response.on('data', function(data) {
            out += data;
        });

        response.on('end', function() {

            console.log(out);

            res.end(out);

        })

    })
    .on('error', function(err) {
        console.log(err);
    })
    .end();

}).listen(server_port, server_ipAddr);

如果你运行它,你会得到这样的东西:

$ node cloudant.get.alldoc.js
{"total_rows":148,"offset":0,"rows":[
{"id":"0fdda996e7b4f11b8a5ab6c9aa002151","key":"0fdda996e7b4f11b8a5ab6c9aa002151","value":{"rev":"1-6eb8654a7ac5a7cb810e87ef30b2a9d5"}},
...
]}

我希望这有助于某人。