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。
使用方式:
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/ # 查看系统状态
nodejs 搭建 RESTful API 服务器的常用包及其简介的更多相关文章
- 使用CodeIgniter框架搭建RESTful API服务
使用CodeIgniter框架搭建RESTful API服务 发表于 2014-07-12 | 分类于 翻译笔记 | 6条评论 在2011年8月的时候,我写了一篇博客<使用Cod ...
- 实现一个 RESTful API 服务器
RESTful 是目前最为流行的一种互联网软件结构.因为它结构清晰.符合标准.易于理解.扩展方便,所以正得到越来越多网站的采用. 什么是 REST REST(REpresentational Stat ...
- 使用 Beego 搭建 Restful API 项目
1 环境准备 首先你需要在你的环境安装以下软件: go:编程语言运行环境 git:版本控制工具 beego:go 语言流行的开发框架 bee:beego 配套的快速搭建工具 你喜欢的数据库:这里以 M ...
- 搭建RESTful API 之 实现WSGI服务的URL映射
javarestfull 搭建参考 http://blog.csdn.net/hejias/article/details/47424511 问题引出:对于一个稍具规模的网站来说,实现的功能不可能通过 ...
- 玩转 SpringBoot 2 快速搭建 | RESTful Api 篇
概述 RESTful 是一种架构风格,任何符合 RESTful 风格的架构,我们都可以称之为 RESTful 架构.我们常说的 RESTful Api 是符合 RESTful 原则和约束的 HTTP ...
- (转)nodejs搭建本地http服务器
本文转载自:http://www.cnblogs.com/shawn-xie/archive/2013/06/06/3121173.html 由于不做php相关的东西,懒得装apache,干脆利用no ...
- Go实战--通过gin-gonic框架搭建restful api服务(github.com/gin-gonic/gin)
生命不止,继续 go go go !!! 先插播一条广告,给你坚持学习golang的理由: <2017 软件开发薪酬调查:Go 和 Scala 是最赚钱的语言> 言归正传! 之前写过使用g ...
- Java——搭建自己的RESTful API服务器(SpringBoot、Groovy)
这又是一篇JavaWeb相关的博客,内容涉及: SpringBoot:微框架,提供快速构建服务的功能 SpringMVC:Struts的替代者 MyBatis:数据库操作库 Groovy:能与Java ...
- TP5.0搭建restful API 应用
1.配置环境变量,如果没配置会显示如下错误. 配置方法 1)右键此电脑-> 属性-> 高级系统设置->环境变量->Path 2)在Path后加上php目录的名称 如:E:\PH ...
随机推荐
- [原创]adb使用教程v1.0-----by-----使用logcat快速抓取android崩溃日志
原文再续,书接上回:<使用logcat快速抓取android崩溃日志>中提到的工具包可以下载拉~ <使用logcat快速抓取android崩溃日志>:http://www.cn ...
- 可视化之Earth NullSchool
上两篇我们分别介绍了<Berkeley Earth>和<AQICN>两个网站,今天来看一下Earth NullSchool. 这个网站的特色是风向图,之前有一篇可视化之风向图, ...
- 自己整理的openresty安装步骤
这几天一直在研究对webapi的限流和名单的问题,于是看了开涛博客的方案,于是就用到了openresty,一个把Nginx和lua集成的东西. 下面就是整理的安装方案(简单使用基本可以这么安装) 下载 ...
- [BZOJ1597]土地购买
Description 农夫John准备扩大他的农场,他正在考虑N (1 <= N <= 50,000) 块长方形的土地. 每块土地的长宽满足(1 <= 宽 <= 1,000, ...
- Ubuntu下的iptux和Windows下的飞秋互传文件
1.问题 当Linux下的iptux是安装源里的版本时,存在下面的问题:Windows下的飞秋可以向Linux下的iptux发送文件,iptux接受正常Linux下的iputx给Windows下的飞秋 ...
- JS键盘事件对象之keyCode、charCode、which属性对比
先说一些有关键盘事件的事项:用js实现键盘记录,要关注浏览器的三种按键事件类型,即keydown,keypress和keyup,它们分别对应onkeydown. onkeypress和onkeyup这 ...
- java递归算法实现 数字人民币大写转换
最近穷死了 ,没钱吃饭ing 写点钱给自己吧!public class Test{ public static String getChar(long a){ int b = (int)a; Map ...
- CSS都有哪些选择器?
派生选择器(用HTML标签申明) id选择器(用DOM的ID申明) 类选择器(用一个样式类名申明) 属性选择器(用DOM的属性申明,属于CSS2,IE6不支持,不常用,不知道就算了) 除了前3种基本选 ...
- postgis 中的距离计算
最近在做一个项目,有一个功能想要实现类似于查询附近的人的功能.由于项目的原因数据库只能使用 postgresql,空间查询就使用了 postgis 来实现. 具体业务像这样:业务需要返回附近距自己 1 ...
- css的各种选择器
一.基本选择器 1. * 通用元素选择器,匹配任何元素 2. E 标签选择器,匹配所有使用E标签的元素 3. .info class选择器,匹配所有class属性中包含info的元素 4. #foot ...