Express.js란?
Express.js는 Node.js의 핵심 모듈인 http와 Connect 컴포넌트를 기반으로 하는 웹 프레임워크이다. Express를 사용하면 코드의 복잡성을 낮춰주고 웹애플리케이션 구현 과정의 공통적으로 요구되는 일을 대신 지원해주면서 보다 쉽게 애플리케이션을 구현할 수 있다.
Hello world 예제 구현
다음과 같은 과정을 통해 간단한 Express 앱을 작성할 수 있다.
전제조건 : Node.js 설치
* 설치확인(node.js 버전확인) : node -v
1. 디렉토리 생성
mkdir sample
cd sample
2. 해당 디렉토리에서 npm init (npm 설치)
npm init
3. 해당 디렉토리에 Express 설치
npm install express --save
node-modules : 라이브러리 파일 모음
4. 해당 디렉토리에 백엔드 시작점이 될 index.js 파일 작성
index.js
const express = require('express')
const app = express()
const port = 5000
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
package.json
{
"name": "practice",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1"
}
}
package.json 에서 index.js를 시작스크립트로 지정
5. start 스크립트(index.js)를 시작으로 실행
npm run start
앱은 서버를 시작하며 지정한 5000번 포트에서 연결을 청취하며 라우트에 대한 요청에 Hello World! 로 응답한다.
다른 경로에 대해서는 404 Not Found 로 응답한다.
브라우저에서 로컬호스트를 로드하여 결과물을 확인한다.
'Node.js' 카테고리의 다른 글
[Node.js] 웹 애플리케이션과 몽고 DB 연결 (0) | 2020.09.17 |
---|---|
[Node.js] node.js 개념 정리 (0) | 2020.09.15 |