1. http 모듈 실습 만드는데 초점을 맞춰주세요. 상세한 내용은 REPL에서 다뤄보실 수 있습니다. 폴더 안에 있는 html 파일들은 모두 아래 page에 있습니다. 응답 순서는 writeHead, write, end를 가급적 지켜주세요. 두번 응답을 보낼 수는 없습니다. 오류 발생시에도 응답은 보내줘야 합니다. 아니면 timeout 오류가 나서 응답이 오기 전까진 계속 브라우저가 기다립니다. API 명만 쭉 살펴보는 것만으로 도움이 됩니다. 📝
007_http\html // 파일이름 : 007_http\app1.js
const http = require('http');
const server = http.createServer(function(req, res){
console.log('server가 구동중입니다.');
console.log(req.headers);
console.log(req.method);
console.log(req.url);
res.write('hello world');
res.end();
});
server.listen(8080);
// 파일이름 : 007_http\app2.js
const http = require('http');
const server = http.createServer(function(req, res){
console.log('server가 구동중입니다.');
console.log(req.headers);
console.log(req.method);
console.log(req.url);
res.write(`
<h1>hello world</h1>
<p>hello world</p>
`);
res.end();
});
server.listen(8080);
// 파일이름 : 007_http\app3.js
const http = require('http');
const server = http.createServer(function(req, res){
console.log('server가 구동중입니다.');
console.log(req);
console.log(req.headers);
console.log(req.method);
console.log(req.url);
// get과 post 둘 다 테스트
// post에 관련된 내용은 아래 공식문서 링크 참고
// https://nodejs.org/ko/docs/guides/anatomy-of-an-http-transaction/
// write 여러줄에 end 마지막 한 줄 가능합니다.
res.write(`
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<form action="/" method="get">
id : <input type="text" name='id_value'><br>
pw : <input type="pw" name='pw_value'><br>
<input type="submit" value="login">
</form>
</body>
</html>
`);
res.end();
});
server.listen(8080);
// 파일이름 : 007_http\app4.js
const http = require('http');
const fs = require('fs');
const querystring = require('querystring');
const server = http.createServer(function(req, res){
console.log('server가 구동중입니다.');
// get과 post 둘 다 테스트
if(req.method == 'GET') {
fs.readFile('./test.html', 'utf8', (err, data) => {
console.log(err);
//writeHead대신 setHeader를 사용하여 type을 보낼 수 있음
res.writeHead(200, {'Content-Type':'text/html'});
res.write(data);
res.end();
});
} else if(req.method =='POST') {
req.on('data', function(chunk) {
console.log(chunk.toString());
let data = querystring.parse(chunk.toString());
console.log(data);
res.writeHead(200, {'Content-Type':'text/html'});
res.write(`id : ${data.id_value}, pw : ${data.pw_value}`);
res.end();
});
}
});
server.listen(8080);
// 파일이름 : 007_http\app5.js
const http = require('http');
const fs = require('fs');
const server = http.createServer(function(req, res){
let url = req.url;
if(req.url == '/favicon.ico'){
return res.writeHead(404);
}
if(req.url == '/'){
url = '/html/index.html';
} else if (req.url == '/about'){
url = '/html/about.html';
} else if (req.url == '/product'){
url = '/html/product.html';
} else if (req.url == '/notice'){
url = '/html/notice.html';
} else {
res.writeHead(404);
res.end();
return
}
res.writeHead(200);
// console.log(__dirname + url);
res.end(fs.readFileSync(__dirname + url));
// response.end('helloworld!!' + url);
});
server.listen(8080);
// 파일이름 : 007_http\app6.js
const http = require('http');
const fs = require('fs');
const server = http.createServer(function(req, res){
let url = req.url;
if(req.url == '/favicon.ico'){
return res.writeHead(404);
}
if(req.url == '/'){
url = '/html/index.html';
} else if (req.url == '/about'){
url = '/html/about.html';
} else if (req.url == '/product'){
url = '/html/product.html';
} else if (req.url == '/notice'){
url = '/html/notice.html';
} else if (req.url == '/test.css'){
// 주의! 들어오는 url은 localhost:8080/test.css
url = '/html/test.css';
}else {
res.writeHead(404);
res.end();
return
}
res.writeHead(200);
// console.log(__dirname + url);
res.end(fs.readFileSync(__dirname + url));
// response.end('helloworld!!' + url);
});
server.listen(8080);
파일이름 : 007_http\notice.html
<!DOCTYPE html><html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>notice다!</h1>
</body>
</html>
파일이름 : 007_http\test.html
<!DOCTYPE html><html>
<head>
<title>test</title>
</head>
<body>
<form action="/" method="post">
id : <input type="text" name='id_value'><br>
pw : <input type="pw" name='pw_value'><br>
<input type="submit" value="login">
</form>
</body>
</html>
2. REPL 실습(OS) > const os = require('os');
undefined
> os.arch()
'x64'
> os.platform()
'win32'
> os.type()
'Windows_NT'
> os.cpus() // 저는 16개인데 1개만 사용한다고요? cluster를 사용해서 16개를 모두 사용할 수도 있습니다.
3. REPL 실습(url, querystring) 자주 사용되진 않는 append, set, delete는 실습하지 않았습니다. > const url = require('url')
undefined
> const testURL = new URL('http://www.paullab.co.kr/?subject=notice&num=343')
undefined
> testURL
URL {
href: 'http://www.paullab.co.kr/?subject=notice&num=343',
origin: 'http://www.paullab.co.kr',
protocol: 'http:',
username: '',
password: '',
host: 'www.paullab.co.kr',
hostname: 'www.paullab.co.kr',
port: '',
pathname: '/',
search: '?subject=notice&num=343',
searchParams: URLSearchParams { 'subject' => 'notice', 'num' => '343' },
hash: ''
}
> testURL.searchParams
URLSearchParams { 'subject' => 'notice', 'num' => '343' }
> testURL.searchParams['subject']
undefined
> testURL.searchParams.get('subject')
'notice'
> testURL.searchParams.get('num')
'343'
> testURL.searchParams.getAll('subject')
[ 'notice' ]
> testURL.searchParams.has('hello')
false
> testURL.searchParams.has('num')
true
> testURL.searchParams.keys()
URLSearchParams Iterator { 'subject', 'num' }
> testURL.searchParams.values()
URLSearchParams Iterator { 'notice', '343' }
> const querystring = require('querystring')
undefined
> const pa = url.parse('http://www.paullab.co.kr/?subject=notice&num=343')
undefined
> pa
Url {
protocol: 'http:',
slashes: true,
auth: null,
host: 'www.paullab.co.kr',
port: null,
hostname: 'www.paullab.co.kr',
hash: null,
search: '?subject=notice&num=343',
query: 'subject=notice&num=343',
pathname: '/',
path: '/?subject=notice&num=343',
href: 'http://www.paullab.co.kr/?subject=notice&num=343'
}
> querystring.parse(pa.query)
[Object: null prototype] { subject: 'notice', num: '343' }
> querystring.parse(pa.query)['subject']
'notice'
> querystring.stringify(pa)
'protocol=http%3A&slashes=true&auth=&host=www.paullab.co.kr&port=&hostname=www.p
aullab.co.kr&hash=&search=%3Fsubject%3Dnotice%26num%3D343&query=subject%3Dnotice
%26num%3D343&pathname=%2F&path=%2F%3Fsubject%3Dnotice%26num%3D343&href=http%3A%2
F%2Fwww.paullab.co.kr%2F%3Fsubject%3Dnotice%26num%3D343'
4. express로 넘어가기 전 더 많은 모듈이 있지만 모듈만 쭉 나열하면 재미없는 수업이 될 뿐만 아니라, 기억이 나지도 않기 때문에 무언가를 만들 수 있는 express로 넘어가고 프로젝트마다 필요한 모듈들을 살펴보도록 하겠습니다.