Webアプリケーションの例
var http = require('http') // httpモジュールの読み込み
http.createServer(function(req,res) { // サーバの作成
res.writeHead(200,{'Content-TYpe': 'text/plain'}); // httpヘッダの出力
res.end('Hello World\n'); // 本文の出力
}).listen(1337,'127.0.0.1');
console.log('Server running at http://localhost:1337/'); // コンソールログに出力
node.jsの起動
$ node ファイル名
Webアプリケーションフレームワーク「express」の導入
$ npm install express
サーバモジュールとアプリケーションモジュールの分離
1. サーバモジュールserver.js
var http = require("http");
function start() {
function onrequest(request,response) {
console.log("Request received.");
response.writeHead(200, {content-type": "text/plain"});
response.write("Hello World\n");
response.end();
}
http.createServer(onRequest).listen(1337);
console.log)"Server has started.");
}
exports.start.start;
2. アプリケーションモジュールindex.js
var server = require("./server"):
server.start();
3. Httpサーバの起動
# node index.js
Hapiアプリケーションサーバ
1.導入
$ npm install hapi -save
2.index.js
use 'strict';
const Hapi = require('hapi');
const server = Hapi.server({
host: 'localhost',
port: 8000
});
server.route({
method: 'GET',
path: '/hello',
handler: function(request, h) {
return hello world';
}
});
async function start() {
try {
await server.start();
}
catch (err) {
console.log(err);
process.exit(1);
}
console.log('Server running at:', server.info.url);
};
start();
4.起動
$ node .
3.ブラウザ
http://localhost:8000/hello