简体   繁体   English

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

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

I'm trying to access my couchdb from a node.js server. 我正在尝试从node.js服务器访问我的couchdb。

I've followed the nodejs tutorial, and have set up this simple nodejs server: 我已经按照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/');

I would like to make RESTful http and POST requests to the nodejs server. 我想向nodejs服务器发出RESTful http和POST请求。 The nodejs server should then be able to make GET/POST request to the Couchdb, which responds with JSON objects. 然后,nodejs服务器应该能够向Couchdb发出GET / POST请求,Couchdb使用JSON对象进行响应。

How might I do this? 我怎么能这样做?

First of all I am the author of nano and will use it in this response. 首先,我是nano的作者,并将在此回复中使用它。

Here go some simple instructions to get started with node.js and CouchDb. 这里有一些简单的说明来开始使用node.js和CouchDb。

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

If you have couchdb installed, great. 如果你安装了couchdb,那很好。 If you don't you will either need to install it setup a instance online at iriscouch.com 如果不这样做,您将需要安装它在iriscouch.com上在线设置实例

Now create a new file called index.js . 现在创建一个名为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. 如果您为CouchDB设置了usernamepassword ,则需要将其包含在网址中。 In the following line I added admin:admin@ to the url to exemplify 在接下来的行中,我将admin:admin@添加到url以举例说明

, 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: 理想情况下,您希望从脚本中删除create database,以便它永远运行:

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 . 如果你对如何实现这一点感到好奇,你可以阅读这篇文章,我写了一篇关于node.js的Nano - Minimalistic CouchDB

For more info refer to expressjs and nano . 有关更多信息,请参阅expressjsnano Hope this helps! 希望这可以帮助!

You can use node.js module such as Cradle to work with CouchDB. 您可以使用诸如Cradle之类的 node.js模块来使用CouchDB。

Here is a list of available Node.JS modules: https://github.com/joyent/node/wiki/modules 以下是可用的Node.JS模块列表: https//github.com/joyent/node/wiki/modules

Just make HTTP requests. 只需发出HTTP请求。 I would recommend request 我会建议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);
    }));
}

I have a module ( node-couchdb-api ) I've written for this exact purpose. 我有一个模块( node-couchdb-api )我是为了这个目的编写的。 It has no ORM or other features like that, it's just a simple wrapper for the HTTP API that CouchDB offers. 它没有ORM或其他类似的功能,它只是CouchDB提供的HTTP API的简单包装器。 It even follows the conventions established by Node.JS for async callbacks, making your code that much more consistent all-around. 它甚至遵循Node.JS为异步回调建立的约定,使您的代码更加一致。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将C ++应用程序与node.js服务器连接以获取JSON数据? - How can I connect my C++ application with an node.js server to get JSON data? 我想从HTML文档中获取文本框值,并在节点JS中使用Json文件按下提交按钮时发布它们 - I want to get my textbox values from HTML document and post those when submit button is pressed using Json file in node JS 我如何使用json将Web服务返回的数据放入类中 - how can i get the data returned from my webservice into my classes using json 我如何从AsyncTask访问此Json? - How i can access this Json from my AsyncTask? 如何使用jQuery从静态文件夹访问json文件到cshtml文件? - How can I access a json file from my static folder into a cshtml file using jQuery? 如何使我的Delphi XE5 DataSnap REST服务器返回XML,而不返回JSON? - How do I get my Delphi XE5 DataSnap REST server to return XML and not JSON? 如何使用Node JS将JSON发送到视图 - How can I send my json to my view with node js 杰森; 如何将我的 MongoDB 模型 res 数组作为 json 返回到路由器的 .get? (节点js) - Json; how can I return my res array of MongoDB Models to Router's .get, as json? (Node js) 如何在 Python 中的 JSON 中访问我的元素? - How can i access to my elements in my JSON in Python? Perl:Json:我可以在POST处理中执行GET吗? - Perl : Json : Can I perform a GET within my POST processing?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM