* 본 시리즈는 [위데이터랩]의 Node.js 강의를 매주 수요일 1시간씩 듣고 복습한 기록입니다.
실습 전 기본 지식과 준비사항
프레임워크
Express
- Express 공식 사이트: http://expressjs.com/ko/
Express - Node.js 웹 애플리케이션 프레임워크
Node.js를 위한 빠르고 개방적인 간결한 웹 프레임워크 $ npm install express --save
expressjs.com
- Node.js를 위한 빠르고 간편한 JS 웹 프레임워크 (기본 틀)
- express.js의 기본 포트: 3000
- npm으로 express를 설치해야 함
- 사용량이 압도적으로 많음 (출처: https://npmtrends.com/express-vs-hapi-vs-koa)
npm (Node Package Modules)
- 노드의 패키지 매니저
- 다른 사람들이 만든 소스 코드들을 모아둔 저장소
- 노드의 모듈 패키지 관리 도구로써, 확장 모듈의 관리에 도움
- 세계 최대의 패키지 저장소
- 모듈 수가 굉장히 많음 (출처: http://www.modulecounts.com/)
- npm 사이트에서 여러 패키지를 사용할 수 있음
npm
Bring the best of open source to you, your team, and your company Relied upon by more than 17 million developers worldwide, npm is committed to making JavaScript development elegant, productive, and safe. The free npm Registry has become the center of Java
www.npmjs.com
- 다양한 명령어 확인
- npm [명령어] [타겟 모듈 이름] [옵션]
- npm init : pacakge.json 파일 생성
- npm install [모듈명] (= npm i [모듈명]): package 설치
- npm –v : 설치여부와 함께 npm의 버전 확인
- npm install –g npm : npm 최신 버전 업그레이드
- npm start : 패키지 시작
- npm으로 package 설치하는 명령어 예시
- npm install –g express-generator
- express 패키지 설치
- 명령어 끝에 -g는 global 어디에서든지 사용할 수 있게 전역으로 설치한다는 의미
- npm install body-parser
- 클라이언트 POST request data의 body로부터 파라미터를 추출할 수 있는 모듈
- req.body 코드로 파라미터를 추출하는데 bodyparser를 사용하기 전에는 디폴트 값으로 Undefined 설정
- npm install -D nodemon
- Node.js 개발 시 JS 파일들을 수정할 때마다 node 종료 후 다시 실행해줘야 함
- Nodemon은 파일들을 모니터링하고 있다가 수정될 경우 자동으로 서버를 재실행시켜주는 모듈
- npm install –g express-generator
package.json
- 현재 프로젝트 정보와 사용 중인 패키지에 대한 정보를 담은 파일
- 사용할 패키지는 저마다 고유한 버전이 있으므로 기록 필요 (같은 패키지라도 버전별로 기능이 다를 수 있음)
- package.json 코드 예시
{
"name": "node",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \\"Error: no test specified\\" && exit 1",
"start": "node server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.20.2",
"express": "^4.18.2",
"figlet": "^1.6.0"
},
"devDependencies": {
"nodemon": "^2.0.22"
}
}
TCP/UDP 포트 목록
- https://ko.wikipedia.org/wiki/TCP/UDP의_포트_목록
- 80: HTTP (HyperText Transfer Protocol) - 웹 페이지 전송
- 443: HTTPS - 보안 소켓 레이어 (SSL, Secure Socket Layer) 위의 HTTP (암호화 전송)
npm과 express 활용 실습
npm으로 패키지를 사용하기 전에 준비할 것
- 1. 지난 시간에 만들었던 NODE 폴더에 index.js 파일 생성
- 2. 터미널에 입력: npm init (pacakge.json 파일 생성하는 명령어)
- 입력하면 터미널에 출력되는 데이터에는 계속 엔터 입력해주면 됨
//npm init을 입력하면 터미널에 출력되는 데이터
C:\\DEV\\workspace\\NODE>npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See `npm help init` for definitive documentation on these fields
and exactly what they do.
Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
package name: (node)
version: (1.0.0)
description:
entry point: (index.js)
git repository:
keywords:
author:
license: (ISC)
About to write to C:\\DEV\\workspace\\NODE\\package.json:
{
"dependencies": {
"figlet": "^1.6.0"
},
"scripts": {
"start": "node server.js"
},
"name": "node",
"version": "1.0.0",
"main": "index.js",
"devDependencies": {},
"author": "",
"license": "ISC",
"description": ""
}
Is this OK? (yes)
- 패키지 다운로드 전의 기본 package.json 파일
{
"name": "node",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \\"Error: no test specified\\" && exit 1",
"start": "node server.js"
},
"author": "",
"license": "ISC"
}
npm으로 패키지 사용하기: figlet
- 1. figlet 패키지 설치: 터미널에 npm install figlet 입력
- figlet 링크 (https://www.npmjs.com/package/figlet)
figlet
Creates ASCII Art from text. A full implementation of the FIGfont spec.. Latest version: 1.6.0, last published: a month ago. Start using figlet in your project by running `npm i figlet`. There are 8494 other projects in the npm registry using figlet.
www.npmjs.com
- figlet 패키지 다운로드 후의 package.json 파일
{
"name": "node",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"figlet": "^1.6.0"
}
}
- 2. index.js 파일에 figlet 사용 코드 입력
var figlet = require("figlet");
figlet("Hello World!!", function (err, data) {
if (err) {
console.log("Something went wrong...");
console.dir(err);
return;
}
console.log(data);
});
- 3. 실행시키기: 터미널에 node index.js 입력
- 4. 결과: 터미널에 figlet 결과가 나타남
- figlet 모듈 삭제: 터미널에 npm uninstall figlet 입력
npm으로 패키지 사용하기: express
- 1. express 패키지 설치: 터미널에 npm install express 입력
- express 링크 (https://www.npmjs.com/package/express)
express
Fast, unopinionated, minimalist web framework. Latest version: 4.18.2, last published: 7 months ago. Start using express in your project by running `npm i express`. There are 71934 other projects in the npm registry using express.
www.npmjs.com
- 2. index.js에 express 사용 코드 입력
const express = require('express')
const app = express()
app.get('/', function (req, res) {
res.send('Hello World')
})
app.listen(3000)
- 3. 실행시키기: 터미널에 node index.js 입력
- 4. 브라우저에 http://localhost:3000 입력
- 5. 출력 결과
- 서버 On/Off 방법
- 코드를 수정할 때마다 저장하고 서버를 껐다 켜줘야 정상적으로 작동함
- 서버 켜서 해당 파일 실행하기: 터미널에 node index.js 입력
- 서버 끄기: 터미널에서 Ctrl + C 입력
Express.js 공식 홈페이지의 코드로 만들기
- express 공식 홈페이지의 코드를 index.js에 입력
- Express.js 공식 홈페이지 코드
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
-
- 공식 홈페이지: https://expressjs.com/ko/
Express - Node.js 웹 애플리케이션 프레임워크
Node.js를 위한 빠르고 개방적인 간결한 웹 프레임워크 $ npm install express --save
expressjs.com
- res.send( )에는 문자열, html 코드, JSON, 링크 등 다양한 것이 들어갈 수 있음
const express = require('express')
//app: express의 인스턴스
const app = express()
const port = 3000
//app.get: http 메소드
// '/': 라우팅
//일반 문자열 전송
app.get('/', (req, res) => {
res.send('Hello World!')
})
//HTML 코드 전송
app.get('/apple', (req, res) => {
res.send('<h1>사과는 맛있다</h1>')
})
//JSON 전송
app.get('/cat', (req, res) => {
res.send({'고양이' : '귀엽다'})
})
//링크 전송
app.get('/naver', (req, res) => {
res.send("<a href = 'https://naver.com'>네이버 링크</a>")
})
//라우팅할 때 작성한 name이 {name} 변수로 들어감
app.get('/animal/:name', (req, res) => {
const {name} = req.params
if(name == 'lion'){
res.json({'사자' : '어흥!'})
}else if(name == 'duck'){
res.json({'오리' : '꽥꽥'})
}else if(name == 'dog'){
res.json({'강아지' : '멍멍'})
}else{
res.json({'알 수 없는 동물입니다.' : '다시 확인해주세요.'})
}
})
//해당 포트에 접속하면 콘솔창에 메시지 출력
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
- 출력 화면
'Node.js' 카테고리의 다른 글
[Node.js] 4. HTML 파일을 받아 출력하기 (2) | 2023.05.17 |
---|---|
[Node.js] 2. http 모듈로 API 만들기 (0) | 2023.05.03 |
[Node.js] 1. Node.js 소개 및 설치 (0) | 2023.04.26 |