๐ฑ
ํน์ endpoin์ ๋ํ ์์ฒญ์ ์ ํ๋ฆฌ์ผ์ด์ ์ด ๋๋ตํ๋ ๋ฐฉ์์ ๊ฒฐ์ ํ๋ ๊ฒ
โ ๊ฐ endpoin์ ๋ํด ์ ์ ํ ๋์์ ์ํํ์ฌ ์ ์ ํ ์๋ต์ ์ ๋ฌ
endpoint = HTTP method + URI
๐ฑ
POST /api/users
: HTTP method( ํ์ ) + URI( ์์ )
App routing
get
, post
, put
, delete
, all
โฆRouter level routing
Router
ํจ์ ์ฌ์ฉconst usersRouter = Router();
use
๋ฉ์๋๋ฅผ ์ฌ์ฉํ์ฌ ์ ํ๋ฆฌ์ผ์ด์
์ ํด๋น ๋ผ์ฐํฐ ์ฐ๊ฒฐ// app.js
app.use('/api/users', usersRouter);
// routes/usersRouter.js
usersRouter.put('/:id', (req, res) => {res.send('edit user')});
Postman
๐ฑ GET ์์ฒญ ์ด์ธ์ ๋ค๋ฅธ API ๋ ํ ์คํธ ๊ฐ๋ฅํ๋๋ก ํจ !
Path Parameter
๐ฑ
/api/users/:id
โ:parameter
GET /api/users/:id
params
ํ๋กํผํฐ์์ ํด๋น ๊ฐ ์กฐํ ๊ฐ๋ฅconst { id } = req.params
Query String
๐ฑ
/api/users?page=2&size=5
โ page: 2, size: 5
GET /api/users?page=2&size=5
?
๋ก ์์ํ๊ณ ๊ฐ ๊ฐ์ &
๋ก ์ฐ๊ฒฐkey = value
ํํconst { page, size } = req.query
Request Handler
๐ฑ ์์ฒญ์ ์ฒ๋ฆฌํ๋ ์ฝ๋ฐฑ ํจ์
req
req.params
: Path Parameter์ ์ ๊ทผํ ์ ์๋ ํ๋กํผํฐreq.queries
: Query String์ ์ ๊ทผํ ์ ์๋ ํ๋กํผํฐreq.body
: POST, PUT ์์ฒญ์ Body์ ์ ๊ทผํ ์ ์๋ ํ๋กํผํฐreq.get()
: ์์ฒญ์ HTTP Header ๊ฐ์ ์กฐํํ ์ ์๋ ํ๋กํผํฐ/api/users/:id // -> Path Parmeter: req.params.id
/api/posts?page=2&size=10 // -> req.queries: req.query.page, req.query.size
/req.get('Authorization') // -> req.get()
res
res.send()
: text ํ์์ HTTP ์๋ต ์ ์กres.json()
: JSON ํ์์ HTTP ์๋ต ์ ์กres.render()
: HTML Template์ ์ฌ์ฉํ์ฌ ํ๋ฉด์ ์ ์กres.set()
: ์๋ต์ HTTP Header๋ฅผ ์ ์กres.status()
: ์๋ต์ HTTP Status Code๋ฅผ ์ค์ res.stauts(404).send('User not found');
Middleware( โ intercepter )
๐ฑ ์์ฒญ โ ์๋ต์ ๊ณผ์ ์ฌ์ด์์ ํน์ ์์ ์ ์ํํ๋ ๊ธฐ๋ฅ, chaining ํํ
use
๋ฉ์๋๋ฅผ ์ฌ์ฉํด ๋ฏธ๋ค์จ์ด ์ฐ๊ฒฐ( err, req, res, next )
app.use((req, res, next) => {
req.newProperty = 'Hello World';
next();
});
req
, res
next
: ๋ค์ ๋ฏธ๋ค์จ์ด๋ก ๋์ด๊ฐ๊ธฐnext
ํจ์์ ์ธ์๋ก Error ๊ฐ์ฒด ์ ๋ฌapp.use((req, res, next) => {
if(!isAdmin(req)) {
next(new Error('Not Authorized'));
return;
}
next();
});
err
: 4๊ฐ์ ๋งค๊ฐ๋ณ์๋ฅผ ์ ์ธํ๋ฉด, ์๋ฌ ์ฒ๋ฆฌ ๋ฏธ๋ค์จ์ด๋ก ์ธ์Express: ๋ด์ฅ ๋ฏธ๋ค์จ์ด
express.static()
path
๋ฅผ importํ๊ณ join
๋ฉ์๋๋ฅผ ์ฌ์ฉํ๋ฉด ํ์ฌ ํ๋ก์ ํธ ๊ธฐ์ค ๊ฒฝ๋ก ๋ฌธ์์ด ์์ฑimport path from 'path';
app.use(express.static(path.join(__dirname, 'public')));
express.json()
express.json()
์ ์ฐ๊ฒฐํ์ฌ JSON ํํ์ Body๋ฅผ ์๋์ผ๋ก ์๋ฐ์คํฌ๋ฆฝํธ ๊ฐ์ฒด๋ก ํ์ฑexpress.urlencoded()
express.urlencoded()
์ ์ฐ๊ฒฐํ์ฌ JSON ํํ์ Body๋ฅผ ์๋์ผ๋ก ์๋ฐ์คํฌ๋ฆฝํธ ๊ฐ์ฒด๋ก ํ์ฑ๋ฏธ๋ค์จ์ด ๋ผ์ด๋ธ๋ฌ๋ฆฌ( express ๋ด์ฅ ์ธ )
morgan
npm i morgan