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

你可能感兴趣的文章
npm error Missing script: “server“npm errornpm error Did you mean this?npm error npm run serve
查看>>
npm error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。要解决此问题,1) 安装
查看>>
npm install CERT_HAS_EXPIRED解决方法
查看>>
npm install digital envelope routines::unsupported解决方法
查看>>
npm install 卡着不动的解决方法
查看>>
npm install 报错 EEXIST File exists 的解决方法
查看>>
npm install 报错 ERR_SOCKET_TIMEOUT 的解决方法
查看>>
npm install 报错 Failed to connect to github.com port 443 的解决方法
查看>>
npm install 报错 fatal: unable to connect to github.com 的解决方法
查看>>
npm install 报错 no such file or directory 的解决方法
查看>>
npm install 权限问题
查看>>
npm install报错,证书验证失败unable to get local issuer certificate
查看>>
npm install无法生成node_modules的解决方法
查看>>
npm install的--save和--save-dev使用说明
查看>>
npm node pm2相关问题
查看>>
npm run build 失败Compiler server unexpectedly exited with code: null and signal: SIGBUS
查看>>
npm run build报Cannot find module错误的解决方法
查看>>
npm run build部署到云服务器中的Nginx(图文配置)
查看>>
npm run dev 和npm dev、npm run start和npm start、npm run serve和npm serve等的区别
查看>>
npm run dev 报错PS ‘vite‘ 不是内部或外部命令,也不是可运行的程序或批处理文件。
查看>>