Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 리액트를 다루는 기술
- 자바스크립트
- 머클트리
- 환경변수
- 변수
- 노드
- immer
- 솔리디티
- 이더리움
- 라우터
- node.js 교과서 따라하기
- 우분투
- 벨로포터
- 블록체인
- 전역설치
- 설치
- 시퀄라이즈
- 리액트
- 깃허브
- centos
- 리눅스
- 머클루트
- Docker
- wsl
- 쉘스크립트
- MariaDB
- Sequelize
- wget
- npm
- 일반유저
Archives
- Today
- Total
코드코코
210913 [4장] 4.1 요청과 응답이해하기 본문
1. createServer.js : 서버 만들기
//http서버가 있어야 웹브라우저의 요청을 처리할 수 있으므로 http 모듈 사용.
const http = require('http');
//http모듈에는 createServer메서드가 있음.
http.createServer((req,res)=>{
//여기에 어떻게 응답할지 적는다.
});
2. server1.js : 서버 실행하기
const http = require('http');
http.createServer((req,res)=>{
//응답에 대한 정보를 기록하는 메서드 - 헤더
res.writeHead(200,{'content-Type': 'text/html; chsrset=utf-8'});
//클라이언트로 보낼 데이터 - 본문
res.write('<h1>Hello Node!</h1>');
//응답을 종료하는 메서드
res.end('<p>Hello Server!</p>');
})
//서버연결
.listen(8081,()=>{
//포트는 서버내에서 프로세스를 구분하는 번호.
console.log('8081번 포트에서 서버 대기 중입니다!');
});
3. server1-1.js : 서버 실행의 다른 방법
-아래 ✔ 부분이 실습하면서 놓친 부분
const http = require('http');
✔const server = http.createServer((req,res)=>{
res.writeHead(200,{'content-Type': 'text/html; chsrset=utf-8'});
res.write('<h1>Hello Node!</h1>');
res.end('<p>Hello Server!</p>');
})
//listen 메서드에 콜백함수 대신 서버에 listening 이벤트리스너를 붙여도 됨.
✔server.listen(8089);
server.on('listening',()=>{
console.log('8089번 포트에서 서버 대기 중입니다!');
});
server.on('error',(error)=>{
console.error(err);
});
4.server1-2.js : 한번에 여러서버 실행하기
-createServer를 원하는 만큼 호출하면 된다.
-HTML파일을 fs모듈로 읽어서 전송하여 효율성을 높이자.
const http = require('http');
//1번째 서버
http.createServer((req,res)=>{
res.writeHead(200,{'content-Type': 'text/html; chsrset=utf-8'});
res.write('<h1>Hello Node!</h1>');
res.end('<p>Hello Server!</p>');
})
.listen(8081,()=>{
console.log('8081번 포트에서 서버 대기 중입니다!');
});
//2번째 서버
http.createServer((req,res)=>{
res.writeHead(200,{'content-Type': 'text/html; chsrset=utf-8'});
res.write('<h1>Hello Node!</h1>');
res.end('<p>Hello Server!</p>');
})
.listen(8082,()=>{
console.log('8082번 포트에서 서버 대기 중입니다!');
});
5.server2.js
const http = require('http');
//fs 모듈 : 로컬 파일 및 폴더를 읽기,쓰기,삭제 가능
const fs = require('fs').promises;
http.createServer(async (req, res) => {
//try {실행될 선언들}
try {
//fs모듈로 만들어진 html파일을 읽음.
//데이터 변수에 저장된 버퍼를 그대로 클라이언트에 보내도 됨.
const data = await fs.readFile('./server2.html');
res.writeHead(200, { 'content-Type': 'text/html; chsrset=utf-8' })
res.end(data);
//catch : try 블록에서 예외가 발생했을 때 실행될 선언들
} catch (err) {
console.error(err);
//에러메세지는 일반 문자열이므로 text/plain을 사용
res.writeHead(500, { 'content-Type': 'text/plain; chsrset=utf-8' });
res.end(err.message);
}
})
.listen(8083, () => {//서버연결
console.log('8083번 포트에서 서버 대기 중입니다!');
});
5.server2.html
<!DOCTYPE html>
<html lang="ko">
<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>Node.js 웹 서버</title>
</head>
<body>
<h1>Node.js 웹 서버</h1>
<p>만들 준비 되셨나요?</p>
</body>
</html>
'기록 > node.js 교과서 따라하기' 카테고리의 다른 글
210915 [6장] 6.1 익스프레스 프로젝트 시작하기 (0) | 2021.09.15 |
---|---|
210915 [4장] 4.5 cluster (0) | 2021.09.15 |
210915 [4장] 4.4 https와 http2 (0) | 2021.09.15 |
210914 [4장] 4.3 쿠키와 세션 이해하기 (0) | 2021.09.14 |
210913 [4장] 4.2 REST와 라우팅사용하기 (0) | 2021.09.13 |