Web server & web client with http module
Copy <! DOCTYPE html >
< html lang = "en" >
< head >
< meta charset = "UTF-8" >
< meta name = "viewport" content = "width=device-width, initial-scale=1.0" >
< title >HTTP server test</ title >
</ head >
< body >
< p > Testing web server coding with http module!</ p >
</ body >
</ html >
Copy var http = require("http");
var fs = require("fs");
var url = require("url");
// ์๋ฒ ์์ฑ
http.createServer(function(request, response) {
// url ๋ค์ ์๋ directory/file ์ด๋ฆ parsing
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received!");
// ํ์ผ ์ด๋ฆ์ด ๋น์ด์๋ค๋ฉด index.html ๋ก ์ค์
if (pathname == "/") {
pathname = "/index.html";
}
// ํ์ผ ์ฝ๊ธฐ
fs.readFile(pathname.substr(1), function(error, data) {
if (error) {
console.log(error);
// 1) ํ์ด์ง๋ฅผ ์ฐพ์ ์ ์์ ๋
// HTTP Status: 404 : NOT FOUND
// Content Type: text/plain
response.writeHead(404, { "Content-Type": "text/html" });
} else {
// 2) ํ์ด์ง๋ฅผ ์ฐพ์์ ๋
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/html'});
// ํ์ผ์ ์ฝ์ด์์ responseBody ์ ์์ฑ
response.write(data.toString());
}
// responseBody ์ ์ก
response.end();
});
}).listen(8081);
console.log('Server currently running at http://127.0.0.1:8081/ !');
Copy $ node server.js
Server currently running at http://127.0.0.1:8081/ !
Copy Request for / received!
Request for /favicon.ico received!
{ [Error: ENOENT: no such file or directory, open 'favicon.ico']
errno: -2,
code: 'ENOENT',
syscall: 'open',
path: 'favicon.ico' }
Copy Request for /showmeerror received!
{ [Error: ENOENT: no such file or directory, open 'showmeerror']
errno: -2,
code: 'ENOENT',
syscall: 'open',
path: 'showmeerror' }
Copy Request for /index.html received!
Copy var http = require('http');
// HTTP Request์ option ์ค์ ํ๊ธ
var options = {
host: 'localhost',
port: '8081',
path: '/index.html'
};
// Callback function์ผ๋ก Response ๋ฐ์์ค๊ธฐ
var callback = function(response) {
// response event๊ฐ ๊ฐ์ง๋๋ฉด data๋ฅผ body์ ๋ฐ์์ค๊ธฐ
var body = '';
response.on('data', function(data){
body += data;
});
// end event๊ฐ ๊ฐ์ง๋๋ฉด data ์์ ์ ์ข
๋ฃํ๊ณ ๋ด์ฉ์ ์ถ๋ ฅ
response.on('end', function(){
// data ์์ ์๋ฃ!
console.log(body);
});
// Server์ HTTP Request ๋ ๋ฆฌ๊ธฐ~!
var request = http.request(options, callback);
request.end();
}
Copy $ node client.js
<html>
<head>
<title>HTTP server test</title>
</head>
<body>
<p> Testing web server coding with http module!</p>
</body>
</html>