使用 Node.js + Express + MongoDB 构建 REST API

Node.js – 节点.js

从http://nodejs.org下载并安装Node.js

2. 手册
https://nodejs.org/api/

表达

移动

遵循。以下是简单的步骤。

1. 安装

$ npm install express-generator -g

2. 表达应用生成器运行

$ express restapi; cd restapi; npm install

3. 移动

苹果电脑

$ DEBUG=restapi:* npm start

Windows (Windows 操作系统/窗口操作系统/微软 Windows)

> set DEBUG=restapi:* & npm start

请使用浏览器确认
http://localhost:3000

5.手册
http://expressjs.com/4x/api.html

将node-dev安装为自动重新加载模块,以在进行更改时实现自动重新加载。

1. 安裝

$ npm install -g node-dev

2. 移动

$ node-dev bin/www

MongoDB

安装

请从以下网址进行安装:
http://www.mongodb.org/

如果是Mac的情况,建议从brew安装。

brew install mongodb

在使用brew进行安装时,会出现以下消息,请输入ln和launchctl命令。(或者是mongod命令)

To have launchd start mongodb at login:
    ln -sfv /usr/local/opt/mongodb/*.plist ~/Library/LaunchAgents
Then to load mongodb now:
    launchctl load ~/Library/LaunchAgents/homebrew.mxcl.mongodb.plist
Or, if you don't want/need launchctl, you can just run:
    mongod --config /usr/local/etc/mongod.conf

命令操作

开始运行

mongo

使用以下命令进行操作(详细信息请在官方网站上确认)。

コマンド説明show dbsデータベース一覧表示use [db_name]データベース切り替え。ないときは最初の挿入時に作成される。db現在のデータベース表示helpヘルプdb.getCollectionNames()すべてのコレクションのリスト表示db.[collection_name]コレクションdb.[collection_name].insert({key:value})挿入db.[collection_name].find()検索(SELECT)db.[collection_name].find({key:value})条件検索db.[collection_name].update({key1:value1}, {key2:value2})キーkey1の値がvalue1であるドキュメントのキーkey2の値をvalue2に更新db.[collection_name].update({key1:value1}, {$set:{key2:value2}})キーkey1の値がvalue1であるドキュメントのキーkey2の値をvalue2に更新(値がないときは追加)db.[collection_name].remove({key:value})条件削除

3. 结束

exit

通过Node+Express进行连接

安装MongoDB驱动程序

安装

npm install --save mongodb

2. 手册

由于互联网中包含了新旧信息,所以在选择时需要注意版本。

追加一个用于MongoDB操作的mongo.js文件。

这个地方的写法很依赖版本,因为互联网上混杂了新旧信息,所以需要注意。
我是按照2.1版本的文档来写的。
http://mongodb.github.io/node-mongodb-native/2.1/api

/**
 * node-mongodbのドキュメント
 * http://mongodb.github.io/node-mongodb-native/2.1/
 */
var db;
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');

// Connection URL
var url = 'mongodb://localhost:27017/Sakepedia';

// Use connect method to connect to the Server
MongoClient.connect(url, function(err, mongodb) {
  assert.equal(null, err);
  console.log("Connected correctly to server");
  db = mongodb;
});

var collection = function( name ) {
  return db.collection( name );
}

module.exports = collection;

路由

更改app.js文件

(前略)

// var routes = require('./routes/index');
// var users = require('./routes/users');
var restapi = require( './routes/restapi' );

(中略)

// app.use('/', routes);
// app.use('/users', users);
app.use( '/api', restapi );

(後略)

增加了restapi.js

    • routes.jsをシンプルにしたいので、var collection = require( ‘../mongo’ );部分でMongoDB用ファイルは別ファイルにしている

 

    • Cross Origin制約のためにrouter.allですべてのメソッドにheaderを設定している(もちろん他のドメインに使わせたくない場合は不要)

 

    • パスの:id部分はパラメーターとしてrequest.params.idのように扱える

 

    idを扱うために、var ObjectID = require(‘mongodb’).ObjectID;部分でObjectIDをインポートしている
var express = require( 'express' );
var router = express.Router();
var ObjectID = require('mongodb').ObjectID;
// MongoDB用ファイルを指定
var collection = require( '../mongo' );
var COL = 'restapi';

// For Cross Origin
router.all( '/*', function ( req, res, next ) {
    res.contentType( 'json' );
    res.header( 'Access-Control-Allow-Origin', '*' );
    next();
} );

// GET find
router.get( '/', function ( req, res ) {
  collection(COL).find().toArray(function(err, docs){
    res.send(docs);
  })
} );

// GET find :id
router.get( '/:id', function ( req, res ) {
  collection(COL).findOne( { _id: new ObjectID( req.params.id ) }, {}, function(err, r){
    res.send( r );
  } );
} );


// POST insert data
router.post( '/', function ( req, res ) {
  collection(COL).insertOne( req.body ).then(function(r) {
    res.send( r );
  });
} );

// PUT update data
router.put( '/:id', function ( req, res ) {
  collection(COL).findOneAndUpdate( { _id: new ObjectID( req.params.id ) }, req.body, {}, function(err, r){
    res.send( r );
  } );
} );

// DELETE remove data
router.delete( '/:id', function ( req, res ) {
  collection(COL).findOneAndDelete( { _id: new ObjectID( req.params.id ) }, {}, function(err, r){
    res.send( r );
  } );
} );

module.exports = router;

3. 删除自动生成的无用文件。

$ rm routes/index.js; rm routes/users.js; rm views/*

确认

$ curl http://localhost:3000/api -X POST -d "name=name1"
$ curl http://localhost:3000/api -X POST -d "name=name2"
$ curl http://localhost:3000/api
$ curl http://localhost:3000/api/xxxxxxxxxxxxxxxxxxxxxxxx
$ curl http://localhost:3000/api/xxxxxxxxxxxxxxxxxxxxxxxx -X PUT -d "name=update"
$ curl http://localhost:3000/api
$ curl http://localhost:3000/api/xxxxxxxxxxxxxxxxxxxxxxxx -X DELETE
$ curl http://localhost:3000/api

将之前的内容提交到Git。

建立.gitignore文件(可通过gitignore进行建立)。


# Created by https://www.gitignore.io/api/node

### Node ###
# Logs
logs
*.log
npm-debug.log*

# Runtime data
pids
*.pid
*.seed

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# node-waf configuration
.lock-wscript

# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release

# Dependency directory
# https://docs.npmjs.com/misc/faq#should-i-check-my-node-modules-folder-into-git
node_modules

# Optional npm cache directory
.npm

# Optional REPL history
.node_repl_history

进行git提交

$ git init
$ git add .
$ git commit -m "first commit"

将应用程序部署至Heroku。

遵循。以下是简单的步骤。

1. 创建Heroku账户并安装Heroku Toolbelt。

2. 在Heroku上创建项目。

请注意,如果使用`ita-restapi`部分(名称),会出现错误。

$ heroku login
$ heroku create ita-restapi

会显示应用程序的URL和Git的URL。

https://ita-restapi.herokuapp.com/ | https://git.heroku.com/ita-restapi.git

3. 创建Procfile

web: DEBUG=restapi:* npm start

4. 创建MongoLab

$ heroku addons:create mongolab --app ita-restapi
$ heroku config --app ita-restapi | grep MONGOLAB_URI

蒙古国的URI将被显示。

MONGOLAB_URI: mongodb://heroku_xxxxxxxx:yyyyyyyyyyyyyyyyyyyyyyyyyy@zzzzzzzz.mongolab.com:37185/heroku_xxxxxxxx

更改5.mongo.js的url

为了Heroku创建一个分支。

$ git checkout -b heroku

修改mongo.js。

(前略)
// Connection URL
//var url = 'mongodb://localhost:27017/restapi';
var url = 'mongodb://heroku_xxxxxxxx:yyyyyyyyyyyyyyyyyyyyyyyyyy@zzzzzzzz.mongolab.com:37185/heroku_xxxxxxxx';
(後略)

提交

$ git add .
$ git commit -m "Change mongodb url for heroku"

6. 在Heroku上部署

$ git remote add heroku https://git.heroku.com/ita-restapi.git
$ git push heroku heroku:master

成品(大师级)

广告
将在 10 秒后关闭
bannerAds