LoginSignup
5
1

More than 5 years have passed since last update.

【N予備メモ】nodeを使ってHTTPサーバーを作る

Posted at

※自分用のメモ要素が大きいです

nodeを使ってHTTPサーバーを作る

index.js

 'use strict';
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, {
'Content-Type': 'text/plain; charset=utf-8'
});
res.write(req.headers['user-agent']);
res.end();
});
const port = 8000;
server.listen(port, () => {
console.log('Listening on ' + port);
});

解説

const http = require('http');

NodeにおけるHTTPのモジュールを読み込んでいる。

const server = http.createServer((req, res) => {    
res.writeHead(200, {    
'Content-Type': 'text/plain; charset=utf-8'    
});   
res.write(req.headers['user-agent']);    
res.end();    
});

httpモジュール機能でサーバーを作成。
サーバーにはリクエストを表すオブジェクトの変数req、レスポンスを表すresを受け取る無名関数を渡す。

無名関数の中では、リクエストが来たときの挙動を実装。

res.writeHead(200, {
'Content-Type': 'text/plain; charset=utf-8'
});

200という成功を意味するステータスコードとレスポンスヘッダを書き込んでいる。

res.write(req.headers['user-agent']);

resオブジェクトの、write関数はHTTPのレスポンスの内容を書き出している。
リクエストヘッダのuser-agentの中身を、レスポンスの内容として書き出している。

 res.end();

endメソッド呼び出しレスポンスの書き出しを終了。

    const port = 8000;
server.listen(port, () => {
console.log('Listening on ' + port);
});

HTTPが起動するポートを宣言し、サーバーを起動し、起動した際に実行する関数を渡している。

HTTPサーバーが起動する関数はlisten関数という。

おまけ

res,writeの中身をHTMLにしてhttp://localhost:8000で表示できるらしい

res.write('
'<!DOCTYPE html><html lang="ja"><body><h1>Hello,World!</h1></body></html>'
')

お試しあれ

5
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
1