博客
关于我
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/

你可能感兴趣的文章
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
查看>>
No new migrations found. Your system is up-to-date.
查看>>
No qualifying bean of type XXX found for dependency XXX.
查看>>
No resource identifier found for attribute 'srcCompat' in package的解决办法
查看>>
no session found for current thread
查看>>
No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
查看>>
NO.23 ZenTaoPHP目录结构
查看>>
no1
查看>>
NO32 网络层次及OSI7层模型--TCP三次握手四次断开--子网划分
查看>>
NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
查看>>
Node JS: < 一> 初识Node JS
查看>>
Node Sass does not yet support your current environment: Windows 64-bit with Unsupported runtime(72)
查看>>
Node-RED中使用JSON数据建立web网站
查看>>