πππ
μΉ μλ²λ₯Ό λ§λ€ λ νΈλ¦¬ν κΈ°λ₯μ μ 곡νλ νλ μμν¬
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
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 μ΄λ€.
λΌμ°ν κ³Ό λ‘μ§μ λͺ¨λνλ₯Ό μν΄ μ¬μ©
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) μ νν