index
基础使用
安装
npm i fastify@next
# or
yarn add fastify@next
注意事项
fastify 使用 async/await 或者 promise处理请求后,return
和reply.send
两者二选一
- 想通过
reply.send
返回数据,则不能使用return
- 如果使用
return
,则不要用reply.send()
且不能返回undefined
初始化
import Fastify from 'fastify'
const fastify = Fastify({
logger: true
})
// 路由声明
export default async function routes (fastify, options) {
fastify.get('/', async (request, reply) => {
reply.type('application/json').code(200)
return { hello: 'world' }
})
}
// 注册路由
fastify.register(routes, options)
// 启动服务!
const start = async () => {
try {
await fastify.listen(3000)
} catch (err) {
fastify.log.error(err)
process.exit(1)
}
}
start()
路由
路由声明的方式
- 类似hibi
- 类似express
路由前缀
处理不同版本的api,可以设置相同的路由,不同的前缀来快速实现
- v1/user
- v2/user
fastify.register(require('./routes/v1/users'), { prefix: '/v1' })
fastify.register(require('./routes/v2/users'), { prefix: '/v2' })
校验
请求校验
响应校验
使用示例
类express的初始化
import Fastify from 'fastify'
const fastify = Fastify()
// 通用式处理
function handler (req, reply) {
reply.send(reply.context.config.output)
}
fastify.get('/en', { config: { output: 'hello world!' } }, handler)
fastify.get('/it', { config: { output: 'ciao mondo!' } }, handler)
fastify.listen(3000)
静态服务器
npm install --save @fastify/static
const fastify = require('fastify')()
const path = require('path')
// 添加1个目录
fastify.register(require('@fastify/static'), {
root: path.join(__dirname, 'public'),
// optional: default '/'
prefix: '/public/',
})
// 添加第二个目录
fastify.register(fastifyStatic, {
root: path.join(__dirname, 'node_modules'),
prefix: '/node_modules/',
// the reply decorator has been added by the first plugin registration
decorateReply: false
})
fastify.get('/another/path', function (req, reply) {
return reply.sendFile('myHtml.html') // serving path.join(__dirname, 'public', 'myHtml.html') directly
})
fastify.get('/path/with/different/root', function (req, reply) {
return reply.sendFile('myHtml.html', path.join(__dirname, 'build')) // serving a file from a different root location
})
fastify.get('/another/path', function (req, reply) {
// overriding the options disabling cache-control headers
return reply.sendFile('myHtml.html', { cacheControl: false })
})