OVERVIEW
- Node JS, Express JS에 대해 공부해 보려고 한다.
- 목표: API 연결하기
→ API를 연결하는 방법을 배워서 새로운 프로젝트를 만들어 보는 것이 목표
- bash terminal 사용해보기
Node JS? Express JS?
◼ Node.js란?
- Node.js 는 서버사이드 자바스크립트이며 구글의 자바스크립트 엔진인 V8을 기반으로 구성된 일종의 소프트웨어 시스템이다
[출저 구름Edu]
◼ Express.js란?
- Express.js, 또는 간단히 익스프레스는 Node.js를 위한 웹 프레임워크의 하나로, MIT 허가서로 라이선스되는 자유-오픈 소스 소프트웨어로 출시되었다. 웹 애플리케이션, API 개발을 위해 설계되었다.
[출저 wiki]
Express.js 공식 문서로 빠르게 배워보기
1. Installing
mkdir myserver && cd myserver
npm init -y
npm install --save express
💡 만약에 npm init으로 시작 시 처음 시작은 RETURN to accept으로
기본 설정을 마치면 됨. 다만, entry point만 본인이 express를 시작하고자 하는 파일명을 적어주면 된다.
2. HELLO WORLD
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
res.send('안녕하세염!');
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
- Express 불러오고 실행을 시작하는 문
- port넘버 설정
- app은 '안녕하세염!'이라는 respond를 보낸다.
- app이 제대로 작동될 때 node.js에 'example app ~'이라는 문구가 띄어진다.
◼ 로컬에 띄어보기 : node 파일명 명령어 작성
3. basic router
app.METHOD(PATH, HANDLER)
// METHOD: GET, POST, PUT, DELETE
app.get('/user', (req, res) => {
res.send('당신은 유저이군용!')
})
- 특정 엔드포인트를 만드는 방법
- 주소창에 /user를 이어서 쓰면 response를 받을 수 있다.
- response에는 주로 데이터를 받아온다 (json파일)

🥺 벅차오른다.
HTTP 메시지 읽어도 이해되지 않았는데 이제 바로 이해될 것만 같은...🌟
4. Serving static files in Express
express.static(root, [options])
- express.static이라는 Express의 빌트인 미드웨어 함수 사용
- middleware function :
https://expressjs.com/en/guide/writing-middleware.html
- Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named next.
app.use(express.static())
- 갑자기 app.use()라는 함수를 사용하게 된다.
- app.use() :
https://expressjs.com/en/4x/api.html#app.use
app.use([path,] callback [, callback...])
Mounts the specified middleware function or functions at the specified path: the middleware function is executed when the base of the requested path matches path.
const path = require('path')
app.use(express.static(path.join(__dirname, '경로')))
- path의 경우 npm의 내장모듈로 설치가 필요없다.
- express앱이 다른 디렉토리 경로에서 실행될 경우를 생각해보면 상대경로보다는 절대경로가 훨씬 안정성이 높다!
- public 디렉토리로 경로를 지정하면 가장 먼저 실행되는 파일은 바로 index.html이다 → entry이기 때문에!
터미널 팁
- mkdir : make directory
- cd : change directory
- -y : npm을 시작하되 질문은 모두 yes로 대답.
- --save : local에 저장한다는 뜻
- -g : 전역설치 (PC에 설치됨)
- 명령어 취소하고 재입력 : ctrl + c 누르면 입력창 생성
그외
npm library -nodemon
npm i -g nodemon
- nodemon 라이브러리는 코드 변경 후 저장 시 자동으로 새로고침됨.
nodemon 파일명
__dirname //현재 file명을 제외한 절대 경로
__filename //현재 file명을 합한 절대 경로
느낀점
사실 API를 사용하기 위해서는 어느정도 백엔드 지식이 필요하다. 근데 뭔가 백엔드를 배울 시간을 쓰는게 효율적인가?에 대해 계속 고민해왔고 오늘 공부한 이후로 오히려 고민했던 시간이 후회된다 😪
개인적으로 다 하고 API를 넣어보는 프로젝트를 만들면 항상 지문으로는 이해가 가지 않았던 HTTP Method와 REST API등 다양한 지식들이 이해가 될거같다