【Node.js】使用fastify搭建一个web服务
2017-12-18 10:12
1096 查看
前言
目前使用node.js搭建web服务,可以使用原生的http模块进行搭建,也有express、restify和fastify。fastify框架相对于前两中框架,更加轻巧、数据解析能力更强。先用fastify框架搭建一个web服务。API
搭建之前先说下将要使用到的API。fastify.register(plugin, [options])
在fastify框架中,它将一切资源都认为是一个插件,包括静态资源、路由、服务等。register将会创建一个新的作用域,如果你需要在register中使用decorate,这个变化将不会在register实例上展现。下文将讲述,如何处理这种情况。fastify.decorate(attr,expression)
使用decorate可以对register实例的属性进行修改。Server
//app.js const fastify = require('fastify')(); fastify.addHook('onRequest', (req, res, next) => { console.log(req.url); next(); }) fastify.register(require('./route/our-db-connector'), { url: 'mongodb://***' }); fastify.register(require('./route/our-first-route'),{ prefix: '/v1' }); fastify.listen(3000, function (err) { if (err) throw err fastify.log.info(`server listening on ${fastify.server.address().port}`) })
fastify提供有hook机制,可以对request、response、send等进行监听。
register注册两个插件,数据库实例和路由实例
监听3000端口
连接MongoDB数据库
//our-db-connector.js const fp = require('fastify-plugin') const MongoClient = require('mongodb').MongoClient; async function db (fastify, options) { const url = options.url delete options.url const db = await MongoClient.connect(url, options) fastify.decorate('mongo', db) } module.exports = fp(db)
在这里需要注意的是decorate这个API的使用,因为register会创建新的作用域,但同时需要在fastify实例(即app.js)上绑定db对象。如果想要在register中使用decorate扩展基础服务中的fastify,你需要告诉fastify不再创建新的作用域,这里有两种解决方案。
方案一:使用fastify-plugin模块
const fp = require('fastify-plugin') module.exports = fp(function (fastify, opts, next) { fastify.decorate('utility', () => {}) next() }, '0.x')
方案二:使用’skip-override’
function yourPlugin (fastify, opts, next) { fastify.decorate('utility', () => {}) next() } yourPlugin[Symbol.for('skip-override')] = true module.exports = yourPlugin
在这里推荐使用方案一,便于维护。本文使用的是方案一。
路由
//our-first-route.js let opts = { name:{ schema:{ body:{ type:'string', } } } } async function routes (fastify,options,next) { const collection = fastify.mongo.collection('user') fastify.get('/', async (request, reply) => { return { hello: 'world' } }) fastify.get('/name/:name',opts.name,async (request,reply) =>{ return {name:name} }) } module.exports = routes
调用app.js的fastify实例上的数据库,即fastify.mongo。
fastify支持async/await,这种情况下,只需要return,请求就会结束。
fastify支持schame,即我们看到的/name/:name后面的参数,用户可以预先定义请求的参数类型,以及返回的数据类型。若,数据类型不匹配时,会报错。这一机制,也是fastify在请求处理比express、restify都快的原因所在。
运行
node app.js打开浏览器,在地址栏输入127.0.0.1:3000/v1。
为什么是v1?这是在app.js中有设置前置的原因,fastify.register(require(‘./route/our-first-route’),{ prefix: ‘/v1’ });
相关文章推荐
- 编写一个使用 Node.js/MongoDB Web 服务的 iOS 应用
- 建立一个node.js服务器(使用express搭建第一个Web环境)
- 【node.js】使用node.js搭建一个本地web服务器
- node入门笔记:使用node.js搭建一个简单的服务
- 使用WinWebMail 简单搭建一个局域网邮件服务 并 测试
- 使用 Node.js 和 IBM Mobile Web Push 构建一个实时的营销应用程序
- 一个nodejs+mongodb搭建的博客,使用module: ejs, express, mongodb, underscore等,不错的入门文章
- 使用node.js快速搭建简易本地HTTP服务
- 使用 Node.js 搭建一个 API 网关
- (NodeJS学习文章收集三) node.js基于express框架搭建一个简单的注册登录Web功能
- 第8章-使用Express.js和Hapi构建Node.js-REST-API服务-8.4.重构:使用Hapi搭建REST API服务器
- 使用Node.js搭建静态资源服务详细教程
- 使用Node.js快速搭建WebSocket server
- 建立node.js服务器(使用express搭建Web环境)
- Node.js学习--搭建一个简单的带有get/post接口的服务
- 使用 Node.js、Express、AngularJS 和 MongoDB 构建一个Web程序
- 使用express搭建第一个Web应用【Node.js初学】
- 为一个 iOS 应用编写一个简单的 Node.js/MongoDB Web 服务
- node.js基于express框架搭建一个简单的注册登录Web功能
- 使用NodeJS+AngularJS+MongoDB实现一个Web数据扒取-分析-展示的系统