开发者

How can I access my couchdb from my node server using REST/JSON/GET/POST?

开发者 https://www.devze.com 2023-03-30 06:11 出处:网络
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:

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?


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!


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. :)


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


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

精彩评论

暂无评论...
验证码 换一张
取 消