Node.js + Express + MongoDB + Herokuで簡単なAPIを作ってみる

January 03, 2016

JavaScriptでサーバーサイドを作ってみたくてやってみた。

下準備

まず、下準備。

$ mkdir node-express-mongodb-heroku $ cd node-express-mongodb-heroku $ npm init $ npm install express —save $ npm install mongoose —save $ npm install body-parser —save

mongoldbの設定。

$ mongo

use node-express-mongodb-heroku switched to db node-express-mongodb-heroku db.createCollection(‘shop’) { “ok” : 1 } show collections shop quit()

Expressのコードを記述

少しだけカスタマイズしましたが、ほとんど「Node.js + Express 4.x + MongoDB(Mongoose)でRESTfulなjsonAPIサーバの作成を丁寧に解説する.+ テストクライアントを用いたAPIテストまで - Qiita」を参考にしています。こちらの記事は丁寧な説明とスクリーンショット付きなのでオススメです。

server.js

var express = require(‘express’); var bodyParser = require(‘body-parser’);

var port = process.env.PORT || 3000; var app = express(); app.use(bodyParser.urlencoded({ extended: true})); app.use(bodyParser.json());

var mongoose = require(‘mongoose’); mongoose.connect(‘mongodb://localhost/node-express-mongodb-heroku’);

var Shop = require(‘./app/models/shop’);

var router = express.Router();

router.use(function(req, res, next) { console.log(‘Something is happening.’); next(); });

router.get(’/’, function(req, res) { res.json({ message: ‘Successfully posted a test message.’ }); });

router.route(‘/shops’) .post(function(req, res) { var shop = new Shop(); shop.shop_id = req.body.shop_id; shop.name = req.body.name; shop.address = req.body.address;

    shop.save(function(err) {
        if (err) {
          res.send(err);
        }
        res.json({ message: 'Shop created!' });
    });
})
.get(function(req, res) {
    Shop.find(function(err, shops) {
        if (err) {
          res.send(err);
        }
        res.json(shops);
    });
});

app.use(‘/api’, router); app.listen(port); console.log(‘listen on port ’ + port);

shop.js

var mongoose = require(‘mongoose’); var Schema = mongoose.Schema;

var ShopSchema = new Schema({ shop_id: { type: String, required: true, unique: true}, name: String, address: String }); module.exports = mongoose.model(‘Shop’, ShopSchema);

疎通確認

Paw で確認しました。

スクリーンショット 2016 01 03 18 46 21

Herokuにアップロード

$ vi Procfile web: node server.js $ heroku version $ heroku create node-express-mongodb-heroku $ heroku addons:create mongolab $ heroku config | grep MONGOLAB_URI git push heroku master

heroic config | grep MONGOLAB_URLで見つかったURLをmongodbのconnectの所でlocalhostに当てていた部分と入れ替える。環境変数とかちゃんと使ってやるのが良さそう。

疎通確認

スクリーンショット 2016 01 03 19 25 39

結構すんなりいった。Nodeで簡単なAPIができた〜。

参考


Profile picture

Written by morizotter who lives and works in Tokyo building useful things. You should follow them on Twitter