起步
安装
npm i fastify --save
第一个服务端应用
// 引入fastify
const fastify = require('fastify')()
// 声明一个路由
fastify.get('/', function (request, reply) {
reply.send({ hello: 'world' })
})
// 启动服务
fastify.listen(3000, function (err) {
if (err) throw err
console.log(`server listening on ${fastify.server.address().port}`)
})
如果想使用
async/await
? 可以查看 Routes#async-await!
Fastify专为性能而设计。为了真正地提升我们的服务器,我们可以按照 JSON Schema 标准序列化响应。
const fastify = require('fastify')()
const opts = {
schema: {
response: {
200: {
type: 'object',
properties: {
hello: { type: 'string' }
}
}
}
}
}
// 声明一个包含输入 schema 的路由
fastify.get('/', opts, function (request, reply) {
reply.send({ hello: 'world' })
})
fastify.listen(3000, function (err) {
if (err) throw err
console.log(`server listening on ${fastify.server.address().port}`)
})
学习更多有关于验证和序列化 Validation and Serialization
Register
如你所见,使用 Fastify 非常容易和方便。但是,将所有路由注册在同一个文件中并不是一个好主意,所以 Fastify 提供了一个实用的方法来解决这个问题, register
:
/* server.js */
const fastify = require('fastify')()
fastify.register(require('./route'))
const opts = {
hello: 'world',
something: true
}
fastify.register([
require('./another-route'),
require('./yet-another-route')
], opts, function (err) {
if (err) throw err
})
fastify.listen(8000, function (err) {
if (err) throw err
console.log(`server listening on ${fastify.server.address().port}`)
})
/* route.js */
module.exports = function (fastify, options, next) {
fastify.get('/', function (req, reply) {
reply.send({ hello: 'world' })
})
next()
}
或者使用 async/await
:
/* route.js */
module.exports = async function (fastify, options) {
fastify.get('/', function (req, reply) {
reply.send({ hello: 'world' })
})
}
Run from CLI
您也可以从 CLI 运行 Fastify,感谢 fastify-cli。这很简单! 只需将以下行添加到您的 package.json
中即可:
{
"scripts": {
"start": "fastify server.js"
}
}
创建服务程序:
// server.js
'use strict'
module.exports = function (fastify, opts, next) {
fastify.get('/', (req, reply) => {
reply.send({ hello: 'world' })
})
next()
}
使用 npm start
运行
npm start
幻灯片和视频
幻灯片
视频
Next
Do you want to learn more? Check out the documentation folder located here!