博客
关于我
hapi.js入门系列(一)——一个简单的Hello World程序
阅读量:611 次
发布时间:2019-03-12

本文共 1369 字,大约阅读时间需要 4 分钟。

安装Hapi框架及其应用实践

一、安装Hapi框架

1. 创建开发环境

首先,我们需要创建一个适合开发的文件夹结构。在终端输入以下命令:

mkdir hapi-project && cd hapi-project

2. 初始化项目文件

为了管理项目依赖,需要初始化package.json文件。运行以下命令:

npm init

3. 安装Hapi框架

根据所需版本安装Hapi。当前示例使用Hapi v20.1.0:

npm install @hapi/hapi --save

【注】:在旧版本Hapi中,使用npm install hapi安装,新版本需用@hapi/hapi指定包名。

二、构建简单的Hello World服务

1. 创建项目入口文件

hapi-project文件夹下新建一个index.js文件,并填入以下代码:

const hapi = require('@hapi/hapi');const start = async () => {    const server = hapi.server({        port: 3000    });    await server.start();    console.log(`Hapi服务已启动,访问地址:${server.info.uri}`);};start();

2. 启动服务

在终端执行命令启动服务:

node ./index.js

运行后,会输出类似以下内容:

server is running at http://localhost:3000

验证服务状态

查看当前运行的服务状态,可以使用以下命令:

Linux系统:

netstat -tlnp | grep 3000

Windows系统:

netstat -ano | find "3000"

查看结果中是否存在0.0.0.0:3000的服务-information,确认服务正常运行。

三、添加路由配置

1. 为服务添加基本路由

在现有的index.js文件中,扩展服务器路由配置。添加路由代码如下:

const hapi = require('@hapi/hapi');const start = async () => {    const server = hapi.server({        port: 3000    });    // 注册主路由    server.route({        method: 'GET',        path: '/',        handler: (request, h) => {            return 'Hello World';        }    });    await server.start();    console.log(`Hapi服务已启动,访问地址:${server.info.uri}`);};start();

2. 测试路由功能

打开浏览器,访问http://localhost:3000,验证是否显示Hello World内容。

注意事项

[注]:在Hapi v20版本中,路由控制器的返回方式已改为直接返回内容,使用return关键字即可,无需通过reply方法.

转载地址:http://lfpxz.baihongyu.com/

你可能感兴趣的文章
Oracle 11g数据库成功安装创建详细步骤
查看>>
Oracle 11g超详细安装步骤
查看>>
Oracle 12c中的MGMTDB
查看>>
Oracle 12c安装报错Installation failed to access the temporary location(无法访问临时位置)...
查看>>
Oracle 9i数据库管理教程
查看>>
ORACLE Active dataguard 一个latch: row cache objects BUG
查看>>
oracle avg、count、max、min、sum、having、any、all、nvl的用法
查看>>
Oracle BEQ方式连接配置
查看>>
oracle Blob保存方式,oracle 存储过程操作blob
查看>>
Oracle BMW Racing sailing vessel帆船图
查看>>
ORACLE Bug 4431215 引发的血案—原因分析篇
查看>>
Oracle Business Intelligence Downloads
查看>>
Oracle cmd乱码
查看>>
Oracle Corp甲骨文公司推出Oracle NoSQL数据库2.0版
查看>>
【Docker知识】将环境变量传递到容器
查看>>
uniapp超全user-agent判断 包括微信开发工具 hbuilder mac windows 安卓ios端及本地识别
查看>>
Oracle DBA课程系列笔记(20)
查看>>
oracle dblink 创建使用 垮库转移数据
查看>>
oracle dblink结合同义词的用法 PLS-00352:无法访问另一数据库
查看>>
Oracle dbms_job.submit参数错误导致问题(ora-12011 无法执行1作业)
查看>>