推荐答案
// www.javascriptcn.com code example
const fastify = require('fastify')({ logger: true });
// 定义一个路由
fastify.get('/', async (request, reply) => {
return { hello: 'world' };
});
// 启动服务器
const start = async () => {
try {
await fastify.listen({ port: 3000 });
fastify.log.info(`Server listening on http://localhost:3000`);
} catch (err) {
fastify.log.error(err);
process.exit(1);
}
};
start();本题详细解读
1. 安装 Fastify
首先,你需要安装 Fastify。可以通过 npm 或 yarn 来安装:
npm install fastify
或者
yarn add fastify
2. 创建 Fastify 实例
在代码中,我们首先导入了 Fastify 模块,并创建了一个 Fastify 实例。logger: true 选项启用了内置的日志记录功能,方便调试和监控。
const fastify = require('fastify')({ logger: true });3. 定义路由
接下来,我们定义了一个简单的 GET 路由。当用户访问根路径 / 时,服务器会返回一个 JSON 对象 { hello: 'world' }。
fastify.get('/', async (request, reply) => {
return { hello: 'world' };
});4. 启动服务器
最后,我们通过调用 fastify.listen 方法来启动服务器。listen 方法接受一个配置对象,其中 port 指定了服务器监听的端口号。在这个例子中,服务器将监听 3000 端口。
// www.javascriptcn.com code example
const start = async () => {
try {
await fastify.listen({ port: 3000 });
fastify.log.info(`Server listening on http://localhost:3000`);
} catch (err) {
fastify.log.error(err);
process.exit(1);
}
};
start();5. 运行应用
将上述代码保存为一个文件(例如 app.js),然后在终端中运行:
node app.js
服务器启动后,你可以通过浏览器或 curl 访问 http://localhost:3000,应该会看到返回的 JSON 数据 { hello: 'world' }。