主题
Hello World
Fastify 的入门非常简单,下面我们通过一个最基本的例子快速上手。
安装 Fastify
你可以通过 npm 或 yarn 安装:
bash
npm install fastify
# 或者
yarn add fastify
编写 Hello World 应用
新建一个文件,例如 app.js
:
js
// app.js
const fastify = require('fastify')({ logger: true });
fastify.get('/', async (request, reply) => {
return { hello: 'world' };
});
fastify.listen({ port: 3000 }, (err, address) => {
if (err) {
fastify.log.error(err);
process.exit(1);
}
fastify.log.info(`Server listening at ${address}`);
});
运行:
bash
node app.js
访问浏览器:http://localhost:3000/
你将看到返回的 JSON:
json
{
"hello": "world"
}
分析说明
fastify.get()
:注册一个 GET 路由reply
可省略,返回值将作为响应主体logger: true
会启用默认日志记录器(Pino)