How to build API server by using nodejs

前置作業

從github取得系統架構

 

有安裝git

未安裝git

git clone https://github.com/VasiliyLiao/nodejs_restful_tutorial.git

專案環境部屬

cd YOUR_PROJECT_REAL_PATH
npm install 
//IN YOUR PROJECT REAL PATH
cp config/db.json.example config/db.json

並更改你的db連線
node index.js
--------------------------
including entity:Card    entityPath: 
including routerGroup:card       routerPath:
the app server has listen on port 3000
the database has connect success.

建立restful  APU routes

標準restful api

方法 路由 名稱 代表含意
get /store index 全部店家列表
post /store new 建立新的單家
get /store/:id show 單一店家詳細資料
put /store/:id update 修改店家資料
delete /store/:id delete 刪除店家

example: 創造一個關於店家(store)的api

store.js(routes)

const router = require('express').Router();

router.route('/')
  .get(function(req, res) {

  })
  .post(function(req, res) {

  });


router.route('/:id')
  .get(function(req, res) {

  })
  .put(function(req, res) {

  })
  .delete(function(req, res) {
   
  });

module.exports = router;

新增一個過濾id的param中介層

router.param('id', function(req, res, next) {
  const id = req.params.id;
  next();
});

每當routes裡面有包含:id的就會進入這行route做過濾動作

連接資料庫

使用ODM Mongoose

進行與資料庫的連線

//config/database.json
{
  "sql": "mongodb",
  "host": "主機ip",
  "port": 27017,
  "database": "資料庫",
  "username": "資料庫帳號",
  "password": "資料庫密碼"
}

Entity 與資料庫操作物件

Entity

位於app/entities,定義自己的資料庫欄位及類型

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

var store= new Schema({
  name: {
    type: String,
    default: ''
  }
});

mongoose.model('Store', store);

搜尋全部方法(find)

const Store = require('mongoose').model('Store');

//找尋全部結果
Store.find(function(err, store) {

});

//找尋全部結果,並且有設置篩選條件
Store.find({
    name: '中友百貨'
}, function(err, store) {

}); 

搜尋單一方法(findOne)

const Store = require('mongoose').model('Store');

//透過篩選條件找尋單一結果
Store.findOne({
    _id:"一個獨立的隨機亂數"
},function(err, store) {

});

建立資料方法(create)

const Store = require('mongoose').model('Store');

//建立一筆資料
Store.create({
    name:"我是一個店"
}, function(err) {

});

更新資料方法(update)

const Store = require('mongoose').model('Store');

//建立一筆資料
Store.update({
  _id: "一個id編號"
}, {
  name: 'i am a store'
}, function(err) {
    
});

刪除資料方法(remove)

const Store = require('mongoose').model('Store');

//建立一筆資料
Store.remove({
    _id: id
}, function(err) {
    
});

將restfulapi與資料操作整合

查看所有店家資料

router.route('/')
  .get(function(req, res) {

    Card.find(function(err, card) {
      if (err) {
        return res.status(500).json({
          statusCode: 500,
          message: 'the server has error'
        });
      }

      return res.status(200).json({
        statusCode: 200,
        message: 'success',
        card: card
      });
    });

  });

How to build API server by using nodejs

By andy26283

How to build API server by using nodejs

  • 129