work hard work smart

专注于Java后端开发。 不断总结,举一反三。
随笔 - 1158, 文章 - 0, 评论 - 153, 阅读 - 186万
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

Fastify 安装与入门

Posted on   work hard work smart  阅读(323)  评论(0编辑  收藏  举报

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 

 

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2020-02-19 SpringBoot自定义监听器
2019-02-19 服务跟踪sleuth和可视化跟踪工具Zipkin
2019-02-19 Feign整合Hystrix
点击右上角即可分享
微信分享提示