常用包

  • 框架:

    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。

使用方式:

var favicon = require('serve-favicon')

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

morgan

使用方式:

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

使用方式:

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 是文档出口)

注释示例:

/**
* @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

使用方式:

// 允许所有跨域请求
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

使用方式:

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-Time

var express = require('express')
var responseTime = require('response-time') var app = express()
// 统计响应进入该中间件到写完响应头的毫秒数
app.use(responseTime())

express-validator

验证规则

// 初始化
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/ # 查看系统状态

最新文章

  1. SOAPUI使用教程-REST Service Mocking
  2. linuxmint 17安装scim输入法
  3. 控件UI性能调优 -- SizeChanged不是万能的
  4. python(5) - time模块
  5. 处理emacs-org模式TODO的一个脚本
  6. CentOS桌面环境如何打开终端以及如何将终端加入右键
  7. 收藏了4年的Android 源码分享
  8. --- Android 设置为A2DP 接收器
  9. Unity应用架构设计(8)——使用ServiceLocator实现对象的注入
  10. HTML调用PC摄像头【申明:来源于网络】
  11. sublime-text3打造markdown编辑器
  12. Linux命令:cd
  13. 1.个人项目 Individual Project
  14. 探索RequestBody报com.alibaba.fastjson.JSONObject cannot be cast to xxx
  15. C++进程间通信之共享内存
  16. PowerDesigner 打印错误
  17. http 三次握手
  18. MFC中UpdateData()函数的使用
  19. Restful&amp;RestSharp
  20. 【arc075F】Mirrored

热门文章

  1. dedecms做好的网站怎么上传到网上?
  2. 2015阿里巴巴安全峰会PPT
  3. redis学习(2)--- Redis概述
  4. scrapy架构初探
  5. .net Kafka.Client多个Consumer Group对Topic消费不能完全覆盖研究总结(一)
  6. 【开源】做了一个WinForm窗体的投影组件,能够为窗口添加影子效果
  7. [leetcode-547-Friend Circles]
  8. Thrift总结(二)创建RPC服务
  9. SQL Server 文件结构 与 全局变量,函数
  10. WPF:动态显示或隐藏Listview的某一列