1、fastify安装
npm i fastify --save
2、第一个服务器 main.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | // 加载框架并新建实例 const fastify = require( 'fastify' )({ logger: true }) //申明路由 fastify.get( "/" , function (request, reply){ reply.send({hello: 'world' }) }) // 启动服务 fastify.listen(3000, function (err, address){ if (err){ fastify.log.error(err) process.exit(1) } fastify.log.info(`server listening on ${address}`) }) |
启动 node main.js
访问:http://127.0.0.1:3000/
3、使用async/await创建服务器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | // 加载框架并新建实例 const fastify = require( 'fastify' )({ logger: true }) //申明路由 fastify.get( "/" , function (request, reply){ reply.send({hello: 'world' }) }) // 启动服务 const start = async() => { try { await fastify.listen(3000) } catch (err){ fastify.log.error(err) process.exit(1) } } start(); |
4、第一个插件
在fastify中,一切都是插件(plugin)
创建our-frist-route.js
1 2 3 4 5 6 7 | async function routes(fastify, options){ fastify.get( "/" , async(request, reply) => { return { hello: "world" } }) } module.exports = routes |
创建demo2.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | // 加载框架并新建实例 const fastify = require( 'fastify' )({ logger: true }) fastify.register(require( "./out-first-route" )) // 启动服务 const start = async() => { try { await fastify.listen(3000) } catch (err){ fastify.log.error(err) process.exit(1) } } start(); |
register API是Fastify框架的核心,也是添加路由、插件等的唯一方法。
启动demo2.js node demo2.js
参考: https://www.w3cschool.cn/fastify/fastify-47ju35zi.html
作者:Work Hard Work Smart
出处:http://www.cnblogs.com/linlf03/
欢迎任何形式的转载,未经作者同意,请保留此段声明!
分类:
O. H5、CSS、JS
, Q.JavaScript
标签:
nodejs
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
2020-02-19 SpringBoot自定义监听器
2019-02-19 服务跟踪sleuth和可视化跟踪工具Zipkin
2019-02-19 Feign整合Hystrix