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 |
Tags
- CV
- js
- API
- threejs
- Git
- nodejs
- review
- ps
- figma
- react
- sqlite
- CSS
- GAN
- ML
- python
- postgresql
- Linux
- SOLID
- PRISMA
- ts
- C++
- frontend
- mongo
- DB
- Express
- vscode
- PyTorch
- DM
- html
- UI
Archives
- Today
- Total
아카이브
[Node][Express] Middleware | 01. cookie-parser 본문
패키지 설치가 필요한 미들웨어 입니다.
cookie-parser는 요청으로 전달받은 쿠키를 파싱해주는 미들웨어입니다.
쿠키는 요청의 헤더값으로 전달되며, 원래는 문자열의 형태로 읽어올 수 있습니다.
import express from 'express'
const app = express()
app.get('/login', (req, res) => {
console.log(req.headers.cookie) // cookie 헤더의 값을 출력합니다.
return res.json({ message: 'get method called' })
})
app.listen(3000, () => {
console.log('Server is listening on port 3000')
})
다음과 같이 쿠키로 id=2345값을 요청에 포함시키면, 미들웨어는 이렇게 쿠키 값을 출력합니다.
GET http://localhost:3000/login
Cookie: id=12345
// 출력값
connect.sid=s%3AgMzrEUPCK2F6vPUSLfXF-laXcxtX5K_g.whufLDegwHxnDM5VVQfqjmz2F6DctlG5Oe%2Fro4mxWQA; id=12345
cookie-parser를 사용하면, 이 문자열을 좀 더 보기 쉽도록 객체 형태로 표시할 수 있습니다.
import express from 'express'
import cookieParser from 'cookie-parser' // 추가됨
const app = express()
app.use(cookieParser()) // 추가됨
app.get('/login', (req, res) => {
console.log(req.headers.cookie) // cookie 헤더의 값을 출력합니다.
return res.json({ message: 'get method called' })
})
app.listen(3000, () => {
console.log('Server is listening on port 3000')
})
GET http://localhost:3000/login
Cookie: id=12345
// 출력값
{
'connect.sid': 's:gMzrEUPCK2F6vPUSLfXF-laXcxtX5K_g.whufLDegwHxnDM5VVQfqjmz2F6DctlG5Oe/ro4mxWQA',
id: 12345
}
728x90
'Backend > Node.js' 카테고리의 다른 글
[Node][Express] Middleware | 02. morgan (0) | 2024.08.20 |
---|---|
[Node][Express] route & Router 메소드 (0) | 2024.08.19 |
[Node][Express] 내장 미들웨어 json() / urlencoded() / static() (0) | 2024.08.18 |
[Node][Express] all & use 메소드 (0) | 2024.08.16 |
[Node][Express] Express로 미들웨어 다루기 (0) | 2024.08.12 |
Comments