이어서....
라우팅으로 channel-demo와 user-demo를 합쳐보자.
express만의 장점? 👉🏻 route로 묶어둘 수 있는 것!
Server : Request를 받아서
Router : Request의 URL에 따라 루트(Route)를 정해줌 = 어디로 갈지 길을 정해줌
🤔 Node.js에서의 라우팅이란?
Request(요청)이 날아왔을 때, 원하는 경로에 따라 적절한 방향으로 경로를 안내해주는 것
=> URL, method 에 따라 호출되는 콜백 함수가 다른 것
💭 Node.js가 미리 만들어둔 모듈을 require('모듈 이름');으로 사용한 것처럼 사용할 수 있지않을까?
모듈화 시킬 파일.js
const express = require('express');
//라우터가 확인할 수 있게만 하면됨
const router = express.Router()
router.use(express.json()) //http 외 모듈 'json'
...
module.exports = router
app.js
const express = require('express');
const app = express();
app.listen(7777)
const userRouter = require('./routes/user-demo') //user-demo 소환?
app.use("/", userRouter)
use에서 공통 url 빼줘서 간단하게, 중복되지 않게 할 수 있음
💡 변수명 한꺼번에 쉽게 바꾸기
변수 선언 부분에서 오른쪽마우스 : Rename symbol, 혹은 F2
회원마다 채널을 가지게 ERD를 그려보자!

채널 - 회원 user_id로 연결돼있음. 채널을 선택하면 회원을 알 수 있다!
API도 고쳐야겠다!
=> ❗️개인정보를 url로 주면안되니 body에 넣어주고, 이걸 활용해서 회원에 따른 채널전체를 조회하게 해보자
1) 채널 생성 : POST /channels
- req : body(channelTitle, userId) (cf. 원래 userId는 body X header에 숨겨서)
👉🏻 body는 이미 통째로 가져오니까 코드는 바꿀 필요 없겠다!
- res 201 : `${}님 채널을 응원합니다.`
4) 회원의 채널 전체 조회 : GET /channels
- req : body(userId)
- res 200 : 채널 전체 데이터 list, json array
3) 회원 개별 조회 : GET /users
- req : body(userId)
- res : userId, name
4) 회원 개별 탈퇴 : DELETE /users
- req : body(userId)
- res : `${name}님 다음에 또 뵙겠습니다.` or 메인페이지
channels.js
router
.route('/')
.get((req, res)=>{
var {userId} = req.body
var channels = []; //json array
//예외 처리 2가지
//1) userId가 body에 없으면 --> 로그인하라고 알려줘야겠다.
if(db.size && userId){
db.forEach(function(value, key){
if(value.userId === userId){
channels.push(value)
}
})
//2) userId가 가진 채널이 없으면
if(channels.length){
res.status(200).json(channels)
} else {
rnotFoundChannel()
}
} else {
rnotFoundChannel()
}
}) // 채널 전체 조회
지금은 데이터를 map으로 하고 있기때문에 복잡해질 수밖에 없음!
users.js
//회원가입
router.post('/join', (req, res) => {
console.log(req.body)
if(req.body == {}){
res.status(400).json({
message : `입력 값을 다시 확인해주세요.`
})
}
else {
const {userId} = req.body
db.set(userId, req.body)
res.status(201).json({
message : `${db.get(userId).name}님 환영합니다.`
})
}
})
router
.route('/users')
.get((req, res) => {
let {userId} = req.body;
const user = db.get(userId);
if(user){
res.status(200).json({
userId : user.userId,
name : user.name
})
} else {
res.status(404).json({
message : "회원 정보가 없습나다."
})
}
}) // 회원 개별 조회
.delete((req, res) => {
let {userId} = req.body;
const user = db.get(userId);
if(user ){
db.delete(id)
res.status(200).json({
message : `${user.name}님 다음에 또 뵙겠습니다.`
})
} else {
res.status(404).json({
message : "회원 정보가 없습나다."
})
}
})
module.exports = router
원래 db의 id를 키값으로 사용했던 걸 바디에서 날라온 userId를 키값으로 사용함!
https://github.com/lvyest/Devcourse/tree/main/youtube-demo
Devcourse/youtube-demo at main · lvyest/Devcourse
Contribute to lvyest/Devcourse development by creating an account on GitHub.
github.com
✨ 완성 파일 코드
'Devcourse' 카테고리의 다른 글
| [SQL] DB 실습 - timestamp, 날짜-시간 타입, FK, JOIN (0) | 2026.02.01 |
|---|---|
| <프로그래머스 데브코스 풀스택> 2026-01-30 TIL 데이터베이스(PK, FK, 정규화) (0) | 2026.01.30 |
| <프로그래머스 데브코스 풀스택> 2026-01-25 TIL 미니프로젝트(2) - 로그인, 빈 객체 확인하는 방법, 채널 API (0) | 2026.01.29 |
| <프로그래머스 데브코스 풀스택>2026-01-28 TIL 미니프로젝트 (1) | 2026.01.28 |
| <프로그래머스 데브코스 풀스택> 2026-01-27 TIL(2) 핸들러, 예외처리, == vs === (0) | 2026.01.28 |