avatar
Published on

Express ๋ž€? ๐Ÿš€๐Ÿค”

Authors
  • avatar
    Name
    Haneul
    Twitter

Express

์„ค๋ช…

  • Express๋Š” ์›น ๋ฐ ๋ชจ๋ฐ”์ผ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์„ ์œ„ํ•œ ์ผ๋ จ์˜ ๊ฐ•๋ ฅํ•œ ๊ธฐ๋Šฅ์„ ์ œ๊ณตํ•˜๋Š” ๊ฐ„๊ฒฐํ•˜๊ณ  ์œ ์—ฐํ•œ Node.js ์›น ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ํ”„๋ ˆ์ž„์›Œํฌ์ž…๋‹ˆ๋‹ค.
  • ์ž์œ ๋กญ๊ฒŒ ํ™œ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ์ˆ˜๋งŽ์€ HTTP ์œ ํ‹ธ๋ฆฌํ‹ฐ ๋ฉ”์†Œ๋“œ ๋ฐ ๋ฏธ๋“ค์›จ์–ด๋ฅผ ํ†ตํ•ด ์‰ฝ๊ณ  ๋น ๋ฅด๊ฒŒ ๊ฐ•๋ ฅํ•œ API๋ฅผ ์ž‘์„ฑํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

์„ค์น˜

npm install express

API

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

get() & post()

//GET ๋ฐฉ์‹์˜ METHOD
app.get('/', function (req, res) {
  res.send('hello getMethod')
})

//POST ๋ฐฉ์‹์˜ MEHTOD
app.post('/', function (req, res) {
  res.send('Hello postMethod')
})

Router()

import express from 'express'

const testRouter = expres.Router() // testRouter ์ธ์Šคํ„ด์Šค ์ƒ์„ฑ

//default index route
testRouter.get('/', function (req, res) {
  res.send('Hi!! Home!!')
})

//main route
testRouter.get('/main', function (req, res) {
  res.send('Hi!! Main!!')
})
//end route
testRouter.get('/end', function (req, res) {
  res.send('Hi!! end!!')
})

export default teestRouter

middleware

๋ฏธ๋“ค์›จ์–ด ํ•จ์ˆ˜๋Š” ์š”์ฒญ ์˜ค๋ธŒ์ ํŠธ(req), ์‘๋‹ต ์˜ค๋ธŒ์ ํŠธ (res), ๊ทธ๋ฆฌ๊ณ  ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์˜ ์š”์ฒญ-์‘๋‹ต ์ฃผ๊ธฐ ์ค‘ ๊ทธ ๋‹ค์Œ์˜ ๋ฏธ๋“ค์›จ์–ด ํ•จ์ˆ˜ ๋Œ€ํ•œ ์•ก์„ธ์Šค ๊ถŒํ•œ์„ ๊ฐ–๋Š” ํ•จ์ˆ˜์ž…๋‹ˆ๋‹ค. ๊ทธ ๋‹ค์Œ์˜ ๋ฏธ๋“ค์›จ์–ด ํ•จ์ˆ˜๋Š” ์ผ๋ฐ˜์ ์œผ๋กœ next๋ผ๋Š” ์ด๋ฆ„์˜ ๋ณ€์ˆ˜๋กœ ํ‘œ์‹œ๋ฉ๋‹ˆ๋‹ค.

๋ฏธ๋“ค์›จ์–ด ํ•จ์ˆ˜๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์€ ํƒœ์Šคํฌ๋ฅผ ์ˆ˜ํ–‰ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

  • ๋ชจ๋“  ์ฝ”๋“œ๋ฅผ ์‹คํ–‰.
  • ์š”์ฒญ ๋ฐ ์‘๋‹ต ์˜ค๋ธŒ์ ํŠธ์— ๋Œ€ํ•œ ๋ณ€๊ฒฝ์„ ์‹คํ–‰.
  • ์š”์ฒญ-์‘๋‹ต ์ฃผ๊ธฐ๋ฅผ ์ข…๋ฃŒ.
  • ์Šคํƒ ๋‚ด์˜ ๊ทธ ๋‹ค์Œ ๋ฏธ๋“ค์›จ์–ด ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœ.

ํ˜„์žฌ์˜ ๋ฏธ๋“ค์›จ์–ด ํ•จ์ˆ˜๊ฐ€ ์š”์ฒญ-์‘๋‹ต ์ฃผ๊ธฐ๋ฅผ ์ข…๋ฃŒํ•˜์ง€ ์•Š๋Š” ๊ฒฝ์šฐ์—๋Š” next()๋ฅผ ํ˜ธ์ถœํ•˜์—ฌ ๊ทธ ๋‹ค์Œ ๋ฏธ๋“ค์›จ์–ด ํ•จ์ˆ˜์— ์ œ์–ด๋ฅผ ์ „๋‹ฌํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. ๊ทธ๋ ‡์ง€ ์•Š์œผ๋ฉด ํ•ด๋‹น ์š”์ฒญ์€ ์ •์ง€๋œ ์ฑ„๋กœ ๋ฐฉ์น˜๋ฉ๋‹ˆ๋‹ค.

var express = require('express')
var app = express()

// ๋ฏธ๋“ค์›จ์–ด ํ•จ์ˆ˜ ์ž‘์„ฑ ํ›„ ๋ณ€์ˆ˜ ํ• ๋‹น
var requestTime = function (req, res, next) {
  req.requestTime = Date.now()
  next()
}

// ๋ฏธ๋“ค์›จ์–ด ํ•จ์ˆ˜๋ฅผ ๋กœ๋“œํ•˜๋ ค๋ฉด ๋ฏธ๋“ค์›จ์–ด ํ•จ์ˆ˜๋ฅผ ์ง€์ •ํ•˜์—ฌ app.use()๋ฅผ ํ˜ธ์ถœ
// ๋ฃจํŠธ ๊ฒฝ๋กœ ๋ผ์šฐํŠธ ๋กœ๋“œ ์ „์— ๋จผ์ € ๋กœ๋“œ ๋œ๋‹ค.
app.use(requestTime)

// ์ฝœ๋ฐฑ ํ•จ์ˆ˜๋Š” ๋ฏธ๋“ค์›จ์–ด ํ•จ์ˆ˜๊ฐ€ req(์š”์ฒญ ์˜ค๋ธŒ์ ํŠธ)์— ์ถ”๊ฐ€ํ•˜๋Š” ํŠน์„ฑ์„ ์‚ฌ์šฉํ•œ๋‹ค.
app.get('/', function (req, res) {
  var responseText = 'Hello World!'
  responseText += 'Requested at: ' + req.requestTime + ''
  res.send(responseText)
})
app.listen(3000)

์ฐธ๊ณ  : https://developer.mozilla.org/ko/docs/Learn/Server-side/Express_Nodejs/Introduction https://expressjs.com/ko/