TIL 10. Express

smΒ·2022λ…„ 6μ›” 3일
0

πŸ“πŸ“ŒπŸ“’

πŸ“ Express.js

μ›Ή μ„œλ²„λ₯Ό λ§Œλ“€ λ•Œ νŽΈλ¦¬ν•œ κΈ°λŠ₯을 μ œκ³΅ν•˜λŠ” ν”„λ ˆμž„μ›Œν¬

πŸ“Œ Express κ°€ μ—†λ‹€λ©΄?


const http = require('http') //----- 1

const server = http.createServer((req, res) => { //----- 2
  console.log('request received')

  res.setHeader('Content-Type', 'application/json') //----- 3
  res.end(JSON.stringify({ message: "Welcome to JUST CODE server! Http server without express" })) // 4
});

server.listen(8000, () => {
  console.log('server is running on PORT 8000')
}) // 5
  1. Node.js λ‚΄μž₯ http λͺ¨λ“ˆμ„ κ°€μ Έμ™€μ„œ λ³€μˆ˜μ— μ €μž₯
  2. req => http request의 정보, res => http resoponse 객체
  3. μš”μ²­μ— λŒ€ν•œ μ‘λ‹΅μ˜ headerλ₯Ό application/json ν˜•νƒœλ‘œ μ„ΈνŒ…
  4. res.end ν•¨μˆ˜λ₯Ό ν†΅ν•΄μ„œ μš”μ²­μ— λŒ€ν•œ 응닡(body에)을 마무리
  5. server λŠ” μ•žμ„œ μƒμ„±ν•œ μ„œλ²„λ₯Ό 의미, listen ν•¨μˆ˜λŠ” 인자둜 ν¬νŠΈλ²ˆν˜Έμ™€ μ½œλ°±ν•¨μˆ˜λ₯Ό λ°›λŠ”λ‹€.
    포트번호둜 μ„œλ²„λ₯Ό μ—΄κ³  μ„œλ²„κ°€ 싀행될 λ•Œμ˜ λ‘œμ§μ„ μ½œλ°±ν•¨μˆ˜ μ•ˆμ—μ„œ μ²˜λ¦¬ν•œλ‹€.

 if (url === '/ping') {
    return res.end(JSON.stringify({ message: '/ pong' }))
  }
  if (url === '/signup' && method === 'POST') return res.end(JSON.stringify({ message: 'νšŒμ›κ°€μž… μ™„λ£Œ!' }))
  if (url === '/login' && method === 'POST') return res.end(JSON.stringify({ message: '둜그인 μ™„λ£Œ!' }))
  if (url === '/products' && method === 'GET') return sendProducts(res)

μœ„μ™€ 같이 λΌμš°νŒ…μ„ 직접 request κ°μ²΄μ—μ„œ urlκ³Ό method에 λ”°λΌμ„œ 쑰건문으둜 μ²˜λ¦¬ν•΄ μ£Όμ–΄μ•Ό ν•œλ‹€.
ν•˜μ§€λ§Œ 점점 더 μ•±μ˜ 규λͺ¨κ°€ 컀지면 μ„œλ²„λ₯Ό μ‹€ν–‰ν•˜λŠ” ν•¨μˆ˜ μ•ˆμ—μ„œ μˆ˜λ§Žμ€ 쑰건문과 λ‘œμ§μ„ λͺ¨λ“ˆν™” ν•΄μ•Όν•œλ‹€. λ”°λΌμ„œ 이λ₯Ό ν•΄κ²°ν•˜κΈ° μœ„ν•΄μ„œ νƒ„μƒν•œ ν”„λ ˆμž„μ›Œν¬κ°€ Express 이닀.

πŸ“Œ Express

λΌμš°νŒ…κ³Ό 둜직의 λͺ¨λ“ˆν™”λ₯Ό μœ„ν•΄ μ‚¬μš©

  1. 쑰건문으둜 λΌμš°νŒ…μ„ μ²˜λ¦¬ν–ˆλ˜ 것에 λΉ„ν•΄ κ°„νŽΈ
  2. 각각의 μš”μ²­μ„ μ²˜λ¦¬ν•˜λŠ” ν•¨μˆ˜μ˜ 뢄리

const http = require('http')
const express = require('express')
const { sendProducts } = require('./sendProducts2')

const app = express()
app.use(express.json())

app.get('/ping', (req, res) => {
  res.json({ message: '/ pong' })
})

app.post('/signup', (req, res) => {res.json('signup success')}) // 첫번째 μΈμžμ—λŠ” endpoint url 을 κΈ°μž…ν•˜κ³ ,
app.post('/login', (req, res) => {res.json('login success')}) // 각각의 μš”μ²­μ— λŒ€ν•΄ 핸듀링 ν•˜λŠ” ν•¨μˆ˜λ₯Ό λ‘λ²ˆμ§Έ 인자둜 λ„£μŠ΅λ‹ˆλ‹€.
app.get('/products', sendProducts(req, res))

const server = http.createServer(app)

server.listen(8000, () => {
  console.log('server is listening on PORT 8000')
})

✍ app.method('path',handler function) 의 ν˜•νƒœ

profile
Today I Learned

0개의 λŒ“κΈ€