nodejs 搭建 RESTful API 服務器的經常使用包及其簡介

經常使用包

  • 框架:
    yarn add express
  • 數據庫連接:
    yarn add sequelize
    yarn add mysql2
  • 處理 favicon:
    yarn add serve-favicon
  • 紀錄日誌:
    yarn add morgan
  • 生成文檔:
    yarn add --dev apidoc
  • 解析請求參數:
    yarn add body-parser
  • 設置 HTTP 頭(提升安全性):
    yarn add helmet
  • 文件變更監控(自動重啓):
    yarn add --dev nodemon (啓動服務器腳本中替換 node 便可)
  • 容許 cors 請求:
    yarn add cors
  • 壓縮數據:
    yarn add compression
  • 響應時間:
    yarn add response-time
  • 數據僞造:
    yarn add faker
    – 數據驗證:
    yarn add express-validator
  • 進程管理:
    yarn add --dev pm2
    帶重啓(nodemon用於開發環境),日誌,負載均衡

serve-favicon

優勢:把請求 favicon 的記錄從日誌中去除。緩存 icon 提升性能。使用兼容性最好的 Content-Type。
使用方式:javascript

var favicon = require('serve-favicon')

app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')))

morgan

使用方式:java

var morgan = require('morgan')

app.use(morgan('combined')) //參數可選 dev tiny 或自定義輸出日誌格式,詳見文檔
// 導出日誌文件
var express = require('express')
var fs = require('fs')
var morgan = require('morgan')
var path = require('path')

var app = express()

// create a write stream (in append mode)
var accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), {flags: 'a'})

// setup the logger
app.use(morgan('combined', {stream: accessLogStream}))

body-parser

使用方式:node

var bodyParser = require('body-parser')

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
//設置 false 使用 querystring 解析,處理 ajax 提交的複雜數據更在行。(true 使用 qs 解析)
// parse application/json
app.use(bodyParser.json())

apidoc

使用方式:
生成文檔命令: apidoc -i routes/ -o doc/( routes 是程序入口,doc 是文檔出口)
註釋示例:mysql

/**
 * @api {get} /user/:id Read data of a User
 * @apiVersion 0.3.0
 * @apiName GetUser
 * @apiGroup User
 * @apiPermission admin
 *
 * @apiDescription Compare Verison 0.3.0 with 0.2.0 and you will see the green markers with new items in version 0.3.0 and red markers with removed items since 0.2.0.
 *
 * @apiParam {String} id The Users-ID.
 *
 * @apiSuccess {String}   id            The Users-ID.
 * @apiSuccess {Date}     registered    Registration Date.
 * @apiSuccess {Date}     name          Fullname of the User.
 * @apiSuccess {String[]} nicknames     List of Users nicknames (Array of Strings).
 * @apiSuccess {Object}   profile       Profile data (example for an Object)
 * @apiSuccess {Number}   profile.age   Users age.
 * @apiSuccess {String}   profile.image Avatar-Image.
 * @apiSuccess {Object[]} options       List of Users options (Array of Objects).
 * @apiSuccess {String}   options.name  Option Name.
 * @apiSuccess {String}   options.value Option Value.
 *
 * @apiError NoAccessRight Only authenticated Admins can access the data.
 * @apiError UserNotFound   The <code>id</code> of the User was not found.
 *
 * @apiErrorExample Response (example):
 *     HTTP/1.1 401 Not Authenticated
 *     {
 *       "error": "NoAccessRight"
 *     }
 */

helmet

var express = require('express')
var helmet = require('helmet')

var app = express()

app.use(helmet())

cors

使用方式:git

// 容許全部跨域請求
var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())
// 容許某路由的跨域請求
app.get('/products/:id', cors(), function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for a Single Route'})
})
// 容許某些域的請求
var whitelist = ['http://example1.com', 'http://example2.com']
var corsOptions = {
  origin: function (origin, callback) {
    if (whitelist.indexOf(origin) !== -1) {
      callback(null, true)
    } else {
      callback(new Error('Not allowed by CORS'))
    }
  }
}

app.get('/products/:id', cors(corsOptions), function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for a whitelisted domain.'})
})
// 容許 GET/POST 之外的請求
app.options('/products/:id', cors()) // enable pre-flight request for DELETE request
app.del('/products/:id', cors(), function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for all origins!'})
})

// 對全部路由容許
app.options('*', cors()) // include before other routes

compression

使用方式:github

var compression = require('compression')
var express = require('express')

var app = express()
app.use(compression({filter: shouldCompress}))

function shouldCompress (req, res) {
  if (req.headers['x-no-compression']) {
    // don't compress responses with this request header
    return false
  }

  // fallback to standard filter function
  return compression.filter(req, res)
}

response-time

使用方式:
該中間件將響應時間寫在響應頭 X-Response-Timeweb

var express = require('express')
var responseTime = require('response-time')

var app = express()
// 統計響應進入該中間件到寫完響應頭的毫秒數
app.use(responseTime())

express-validator

驗證規則ajax

// 初始化
app.use(expressValidator())
// this line must be immediately after any of the bodyParser middlewares!

// 檢查參數是否符合標準
req.check('testparam', 'Error Message').notEmpty().isInt()

// 將參數轉化爲
req.sanitize('postparam').toBoolean()

// 返回驗證結果
req.getValidationResult().then(function(result) {
  // do something with the validation result
})

pm2

pm2 start app.js --name="api" # Start application and name it "api"
pm2 stop all                  # Stop all apps
pm2 logs                      # Display logs of all apps
pm2 web     後訪問     http://localhost:9615/        # 查看系統狀態
相關文章
相關標籤/搜索