尝试使用NodeJS框架hapi
我总结了关于Hapi框架的研究。
动力
-
- NodeJSで何かしらコードを書きたい
- 簡単な記述で書きたい(細かい設定等気にしたくない
选择hapi的原因
我觉得有一部分可以使用JSON格式进行编码,这样更容易上手。(主观)
安装hapi
需要安装hapi v17.0.0(截至2018年2月是最新版本)。
需要node.js版本v8.9.0或更高。
npm install --save hapi@17.0.0
当我搜索日本语言的hapi的文章时,只能找到2015年左右的文章。虽然有一些关于hapi v10时期的文章,但它们都无法运行… 将这种成长视为积极的一面,我们将继续前进。
执行Hapi示例代码
根据官方网站(https://hapijs.com)的”开始”部分进行操作。
创建以下样本代码。
所做的是
-
- hapiモジュールの呼び出し
-
- serverのIP(localhost),ポート(8000)の指定
-
- ルーティングの指定
HTTPのリクエストメソッドの指定(GET,PUT,POST,DELETE等)
パスの指定(localhost:8000/helloで呼び出せる
呼び出し時のハンドラ(関数)の指定
サーバの実行
'use strict';
const Hapi = require('hapi');
// Create a server with a host and port
const server = Hapi.server({
host: 'localhost',
port: 8000
});
// Add the route
server.route({
method: 'GET',
path:'/hello',
handler: function (request, h) {
return 'hello world';
}
});
// Start the server
async function start() {
try {
await server.start();
}
catch (err) {
console.log(err);
process.exit(1);
}
console.log('Server running at:', server.info.uri);
};
start();
使用下列命令启动服务器。
node server.js
访问 localhost:8000/hello 时,会显示 “hello world”。