Hapi是一个基于Node.js的Web框架,具有具有插件化、可扩展和高度可测试的特性,使其成为构建Web应用程序和API的理想选择。在本文中,我们将探讨如何使用Hapi框架构建一个小程序的后端。
安装Hapi
- 在命令行中输入以下命令安装Hapi:
npm install hapi --save
- 对于本地开发,你需要安装
nodemon来监听更改并自动重启服务器:
npm install nodemon --global
创建项目
现在Hapi已安装,接下来我们将使用Hapi来创建一个简单的API。
- 创建一个新项目并进入该目录:
mkdir my-api && cd my-api
- 然后创建一个名为
server.js的文件:
touch server.js
- 打开
server.js文件并添加以下代码:
'use strict';
const Hapi = require('hapi');
// 创建一个服务器对象
const server = new Hapi.Server({
host: 'localhost',
port: 8000
});
// 创建自定义路由
server.route({
method: 'GET',
path: '/',
handler: (request, h) => {
return 'Hello World!';
}
});
// 启动服务器
(async () => {
await server.start();
console.log(`Server running at: ${server.info.uri}`);
})();
运行项目
- 通过命令行切换到项目目录并运行以下命令以启动服务器:
nodemon server.js
- 打开浏览器并访问
http://localhost:8000,即可看到“Hello World!”。
创建数据库连接
在实际的应用程序中,我们往往需要与数据库进行交互。Hapi框架可以整合任何数据库查询库,例如pg (PostgreSQL)、MySQL和MongoDB等。我们将使用pg来连接PostgreSQL数据库。
- 在命令行中输入以下命令安装 pg:
npm install pg --save
- 然后更新
server.js文件的代码如下:
'use strict';
const Hapi = require('hapi');
const { Pool } = require('pg');
// 数据库连接配置
const pool = new Pool({
user: 'your_username',
host: 'your_host',
database: 'your_database',
password: 'your_password',
port: your_port
});
// 创建一个服务器对象
const server = new Hapi.Server({
host: 'localhost',
port: 8000
});
// 创建自定义路由
server.route({
method: 'GET',
path: '/',
handler: async (request, h) => {
const client = await pool.connect();
try {
const res = await client.query('SELECT $1::text as message', ['Hello world!']);
return res.rows[0].message;
} finally {
client.release();
}
}
});
// 启动服务器
(async () => {
await server.start();
console.log(`Server running at: ${server.info.uri}`);
})();
- 在
pool对象的配置中,替换以下数据为您的数据库连接信息:
user: 'your_username',
host: 'your_host',
database: 'your_database',
password: 'your_password',
port: your_port
结论
在本文中,我们使用Hapi框架创建了一个简单的API,并使用pg连接了PostgreSQL数据库。尽管本指南涉及的内容是有限的,但是我们希望它能为您提供一个指导,帮助您在开发Node.js小程序后端时使用Hapi框架。 (PS:有新购阿里云云服务器的小伙伴可以找我V:cloudbiyu,最低20%的实付价格返现节省成本赚外快)。