如何使用 REST/JSON/GET/POST 从节点服务器访问 couchdb?

发布于 2024-12-01 03:16:00 字数 462 浏览 2 评论 0原文

我正在尝试从 Node.js 服务器访问我的 couchdb。

我已经遵循了nodejs教程,并设置了这个简单的nodejs服务器:

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(80, "127.0.0.1");
console.log('Server running at http://127.0.0.1:80/');

我想向nodejs服务器发出RESTful http和POST请求。然后,nodejs 服务器应该能够向 Couchdb 发出 GET/POST 请求,Couchdb 用 JSON 对象进行响应。

我该怎么做?

I'm trying to access my couchdb from a node.js server.

I've followed the nodejs tutorial, and have set up this simple nodejs server:

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(80, "127.0.0.1");
console.log('Server running at http://127.0.0.1:80/');

I would like to make RESTful http and POST requests to the nodejs server. The nodejs server should then be able to make GET/POST request to the Couchdb, which responds with JSON objects.

How might I do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

地狱即天堂 2024-12-08 03:16:00

首先,我是 nano 的作者,并将在本次回复中使用它。

这里有一些开始使用 Node.js 和 CouchDb 的简单说明。

mkdir test && cd test
npm install nano
npm install express

如果你安装了 couchdb,那就太好了。如果不这样做,您将需要安装它并在 iriscouch.com 在线设置一个实例。

现在创建一个名为 <代码>index.js。在里面放置以下代码:

var express = require('express')
   , nano    = require('nano')('http://localhost:5984')
   , app     = module.exports = express.createServer()
   , db_name = "my_couch"
   , db      = nano.use(db_name);

app.get("/", function(request,response) {
  nano.db.create(db_name, function (error, body, headers) {
    if(error) { return response.send(error.message, error['status-code']); }
    db.insert({foo: true}, "foo", function (error2, body2, headers2) {
      if(error2) { return response.send(error2.message, error2['status-code']); }
      response.send("Insert ok!", 200);
    });
  });
});

app.listen(3333);
console.log("server is running. check expressjs.org for more cool tricks");

如果您为 CouchDB 设置了用户名密码,则需要将其包含在网址中。在下面的行中,我将 admin:admin@ 添加到 url 中以举例说明

, nano    = require('nano')('http://admin:admin@localhost:5984')

此脚本的问题是,每次执行请求时它都会尝试创建数据库。第一次创建时就会失败。理想情况下,您希望从脚本中删除创建数据库,以便它永远运行:

var express = require('express')
   , db    = require('nano')('http://localhost:5984/my_couch')
   , app     = module.exports = express.createServer()
   ;

app.get("/", function(request,response) {
    db.get("foo", function (error, body, headers) {
      if(error) { return response.send(error.message, error['status-code']); }
      response.send(body, 200);
    });
  });
});

app.listen(3333);
console.log("server is running. check expressjs.org for more cool tricks");

您现在可以手动创建,甚至可以通过编程方式进行创建。如果您对如何实现这一目标感到好奇,您可以阅读我不久前写的这篇文章 Nano - 适用于 Node.js 的简约 CouchDB

有关更多信息,请参阅 expressjs纳米。希望这有帮助!

First of all I am the author of nano and will use it in this response.

Here go some simple instructions to get started with node.js and CouchDb.

mkdir test && cd test
npm install nano
npm install express

If you have couchdb installed, great. If you don't you will either need to install it setup a instance online at iriscouch.com

Now create a new file called index.js. Inside place the following code:

var express = require('express')
   , nano    = require('nano')('http://localhost:5984')
   , app     = module.exports = express.createServer()
   , db_name = "my_couch"
   , db      = nano.use(db_name);

app.get("/", function(request,response) {
  nano.db.create(db_name, function (error, body, headers) {
    if(error) { return response.send(error.message, error['status-code']); }
    db.insert({foo: true}, "foo", function (error2, body2, headers2) {
      if(error2) { return response.send(error2.message, error2['status-code']); }
      response.send("Insert ok!", 200);
    });
  });
});

app.listen(3333);
console.log("server is running. check expressjs.org for more cool tricks");

If you setup a username and password for your CouchDB you need to include it in the url. In the following line I added admin:admin@ to the url to exemplify

, nano    = require('nano')('http://admin:admin@localhost:5984')

The problem with this script is that it tries to create a database every time you do a request. This will fail as soon as you create it for the first time. Ideally you want to remove the create database from the script so it runs forever:

var express = require('express')
   , db    = require('nano')('http://localhost:5984/my_couch')
   , app     = module.exports = express.createServer()
   ;

app.get("/", function(request,response) {
    db.get("foo", function (error, body, headers) {
      if(error) { return response.send(error.message, error['status-code']); }
      response.send(body, 200);
    });
  });
});

app.listen(3333);
console.log("server is running. check expressjs.org for more cool tricks");

You can now either manually create, or even do it programmatically. If you are curious on how you would achieve this you can read this article I wrote a while back Nano - Minimalistic CouchDB for node.js.

For more info refer to expressjs and nano. Hope this helps!

零時差 2024-12-08 03:16:00

我有一个模块(node-couchdb-api),我为此目的而编写。它没有 ORM 或其他类似功能,它只是 CouchDB 提供的 HTTP API 的简单包装器。它甚至遵循 Node.JS 为异步回调建立的约定,使您的代码更加一致。 :)

I have a module (node-couchdb-api) I've written for this exact purpose. It has no ORM or other features like that, it's just a simple wrapper for the HTTP API that CouchDB offers. It even follows the conventions established by Node.JS for async callbacks, making your code that much more consistent all-around. :)

镜花水月 2024-12-08 03:16:00

您可以使用 Node.js 模块(例如 Cradle)来使用 CouchDB。

以下是可用 Node.JS 模块的列表: https://github.com/joyent/node/维基/模块

You can use node.js module such as Cradle to work with CouchDB.

Here is a list of available Node.JS modules: https://github.com/joyent/node/wiki/modules

沦落红尘 2024-12-08 03:16:00

只需发出 HTTP 请求即可。我建议 request

这是一个示例 来自我的代码

request({
    "uri": this._base_url + "/" + user._id,
    "json": user,
    "method": "PUT"
}, this._error(cb));

这是另一个示例来自我的代码

// save document
"save": function _save(post, cb) {
    // doc changed so empty it from cache
    delete this._cache[post.id];

    // PUT document in couch
    request({
        "uri": this._base_url + "/" + post._id,
        "json": post,
        "method": "PUT"
    }, this._error(function _savePost(err, res, body) {
        if (body) {
            body.id = post.id;
            body.title = post.title;
        }
        cb(err, res, body);
    }));
}

Just make HTTP requests. I would recommend request

Here's an example from my code

request({
    "uri": this._base_url + "/" + user._id,
    "json": user,
    "method": "PUT"
}, this._error(cb));

Here's another example from my code

// save document
"save": function _save(post, cb) {
    // doc changed so empty it from cache
    delete this._cache[post.id];

    // PUT document in couch
    request({
        "uri": this._base_url + "/" + post._id,
        "json": post,
        "method": "PUT"
    }, this._error(function _savePost(err, res, body) {
        if (body) {
            body.id = post.id;
            body.title = post.title;
        }
        cb(err, res, body);
    }));
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文