
2023.12.06(수)
설치 : npm i express
Simple usage
const express = require('express')
const app = express()
app.get('/', function (req, res) {
res.send('Hello World')
})
app.listen(3000)
기본 형태
app.METHOD(PATH, HANDLER)
app : express instance
METHOD : 소문자 HTTP request method (get, post, put, patch, delete, head, connect, options, trace)
PATH : server path → 변수 및 정규 표현식 사용 가능
req.params에 key-value 형태로 mapping됨 (value는 String 형태로 저장됨에 주의):param_nameapp.get('/users/**:userId**/books/**:bookId**', (req, res) => {
res.send(req.params)
})Request URL: http://localhost:3000/users/**34**/books/**8989**
req.params: { "userId": "34", "bookId": "8989" }-)과 dot(.)은 문자 그대로 해석되므로 목적에 맞게 사용 가능Route path: /flights/**:from-:to**
Request URL: http://localhost:3000/flights/LAX-SFO
req.params: { "from": "LAX", "to": "SFO" }Route path: /plantae/**:genus.:species**
Request URL: http://localhost:3000/plantae/Prunus.persica
req.params: { "genus": "Prunus", "species": "persica" }:param_name(regex)\)에 escape 문자를 사용해야함 (\d+ → \\d+)Route path: /user/**:userId(\\d+)**
Request URL: http://localhost:3000/user/42
req.params: {"userId": "42"}HANDLER : route가 매칭되었을 때 실행될 function
기본적으로 handler function은 request와 response 객체를 parameter로 받음
추가적으로 next() 객체를 이용해 단계적으로 처리 가능
app.get('/example/b', (req, res, **next**) => {
console.log('the response will be sent by the next function ...')
**next()**
}, (req, res) => {
res.send('Hello from B!')
})const cb0 = function (req, res, **next**) {
console.log('CB0')
**next()**
}
const cb1 = function (req, res, **next**) {
console.log('CB1')
**next()**
}
const cb2 = function (req, res) {
res.send('Hello from C!')
}
app.get('/example/c', [cb0, cb1, cb2])const cb0 = function (req, res, **next**) {
console.log('CB0')
**next()**
}
const cb1 = function (req, res, **next**) {
console.log('CB1')
**next()**
}
app.get('/example/d', [cb0, cb1], (req, res, **next**) => {
console.log('the response will be sent by the next function ...')
**next()**
}, (req, res) => {
res.send('Hello from D!')
})Chainable route handler : app.route()🔗
같은 PATH에 대해 METHOD는 상이할 수 있는데 이 경우 중복과 오타를 줄이기 위해 chainable route handler 사용 가능
활용 예시
하나의 PATH에서 get, post, put 세가지 METHOD에 대한 요청을 처리할 수 있음
app.route('/book')
.get((req, res) => {
res.send('Get a random book')
})
.post((req, res) => {
res.send('Add a book')
})
.put((req, res) => {
res.send('Update the book')
})
Modular, Mountable route handler : express.Router🔗
router를 분리하여 관리하고 싶다면 module로 만들 수 있음
활용 예시
birds.js라는 router file을 따로 생성
const express = require('express')
const router = express.Router()
// middleware that is specific to this router (invoked for any requests passed to this router)
router.use((req, res, next) => {
console.log('Time: ', Date.now())
next()
})
// define the home page route
router.get('/', (req, res) => {
res.send('Birds home page')
})
// define the about route
router.get('/about', (req, res) => {
res.send('About birds')
})
module.exports = router
app에 router module을 load해서 사용
const router = require('./birds')
// ...
// only requests to /birds/* will be sent to our "router"
app.use('/birds', router)
| Method | Description |
|---|---|
| res.download() | Prompt a file to be downloaded. |
| res.end() | End the response process. |
| res.json() | Send a JSON response. |
| res.jsonp() | Send a JSON response with JSONP support. |
| res.redirect() | Redirect a request. |
| res.render() | Render a view template. |
| res.send() | Send a response of various types. |
| res.sendFile() | Send a file as an octet stream. |
| res.sendStatus() | Set the response status code and send its string representation as the response body. |
JSON.stringify(object) : 인자로 받은 객체를 JSON 문자열로 반환 (JavaScript Object → JSON 데이터)JSON.parse(string) : 인자로 받은 문자열을 Javascript Object로 변경해 반환 (JSON 데이터 → JavaScript Object)res.json() methodJSON.stringify()를 사용하여 object parameter를 JSON 문자열로 반환하여 응답을 보냄res.json(null)
res.json({ user: 'tobi' })
res.status(500).json({ error: 'message' })💡 물론 그냥
res.send()를 이용하면 express가 parameter의 type에 따라 적합한 Content-Type으로 지정하여 응답을 보내주긴 하지만 type에 맞는 method를 명시적으로 사용하는 것이 더 바람직하다.
ex)res.send()로 Array나 Object를 보내면 express가 JSON 형식으로 응답을 보냄
express.static(root, [options])root : 정적 자산들(static assets)이 들어있는 root directorypublicapp.use(express.static('public'))http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/images/bg.png
http://localhost:3000/hello.html// public -> files의 순서로 look up
app.use(express.static('public'))
app.use(express.static('files'))/static과 함께app.use('/static', express.static('public'))http://localhost:3000**/static**/images/kitten.jpg
http://localhost:3000**/static**/css/style.css
http://localhost:3000**/static**/js/app.js
http://localhost:3000**/static**/images/bg.png
http://localhost:3000**/static**/hello.htmlconst path = require('path')
app.use('/static', express.static(path.join(__dirname, 'public')))
http모듈을 사용하다가express모듈을 사용해보니 정말 편한 것 같다.😀