2022-02-28 노드 공부흔적남기기3일차

박경현·2022년 2월 28일
0

되게 오랜만에 적는 느낌이 드네..;ㅋㅋㅋ 좀 더 자주 1일 1블로그와
1주일에 1깃허브를 꼭 하자는 다짐을 하고 시작해야겠다

최근 7시에 일어나는건 잘하고있으니까 1시간 더 일찍일어나서 아침을 잘 활용해야겠다.

블로그에 적은 글들은 꼭 다시 보자 내가 정리한거니까 자주 봐야지

고전방식으로 노드 웹서버 만들어보기

블로그 포스팅을 하는데 데이터베이스 없이 만들어보려고 한다

차고로 나는 노드 잘 모르기 때문에 하나부터 열까지 누가봐도 이해할 정도로 세세하게 적어볼 것이다 ㅋㅋㅋ

package.json

httpie는 터미널에서 서버 실행해서 간단하게 정상적으로 작동하는지 확인해 볼수 있는 녀석이다 (choco는 안깔아도 되더라..ㅜ)
typescript와 eslint, prettier는 앞으로도 같이갈 녀석들이다.

간단하게 서버에서 정보를 불러오고 배열에 정보를 저장해보는 걸 해볼거다!!

기초적인 틀 만들기 및 nodemon 쓰기

// @ts-check 
// GET 은 서버에서 정보를 불러올때
// POST 는 서버에 값을 적을때 사용했다
const http = require('http') // 이걸로 http를 사용가능

const server = http.createServer((req.res) => {
})
const PORT = 4000
server.listen(PORT, () => {
	console.log(`The server is listening at port: ${PORT}`)
})

다시 복습해보고자 적어봤다ㅎㅎ

localhost:4000번에 결과를 반환해주는 서버를 만들었다!!

차고로 위에 package.json에 보면 script부분에 server:'nodemon src/main.js'가 있을거다

nodemon을 설치하고 script에 저걸 적어놓은 뒤
터미널에서 npm run server를 해주면
코드 내용이 바뀌어도 다시 서버를 껐다켰다 안해도 자동으로 저장할때마다 새로고침된다

// req는 request의 줄임말로 서버에 요청하는거다
// 새로운 포스팅을 추가로 할때나 req.method 즉 GET인지 POST인지 확인할때 쓰인다.

--> res는 response의 줄임말로 서버에서 클라이언트에 요청한 결과를 반한하는거다

블로그 포스팅 서버를 만들어보자

! 이제 간단한 틀은 알게 되었으니 내용을 추가해서 원하는 서버를 커스텀 해보자!@@

DB를 대체할 간단한 배열을 만들었다 배열 안에는 객체로 넣었으며, 타입스크립트에 맞춰서 적기위해 typedef를 적었다

const server = http.createServer((req,res) => {
	const POSTS_ID_REGEX = /^\/posts\/([a-zA-Z0-9]+)$/
    
    const postIdRegexResult = req.url && POSTS_ID_REGEX.exec(req.url) || undefined
    
    if(req.url === '/posts' && req.method === 'GET'){
    	const result = {
        	posts: posts.map((post) => ({
            	id: post.id,
                title: post.title
            })),
            totalCount: posts.length
        }
        
        res.statusCode = 200
        res.setHeader('Content-Type', 'application/json; charset=utf-8')
        res.end(JSON.stringify(result))
        
    }
    else if(postIdRegexResult && req.method === 'Get') {
    	const postId = postIdRegexResult[1]
        
        const post = posts.find(_post => _post.id === postId) 
        
        if(post) {
        	 res.statusCode = 200
            res.setHeader('Content-Type', 'application/json; charset=utf-8')
            res.end(JSON.stringify(post))
        } else {
        	res.sendCode = 404
            res.end('Not found')
        }
    } else if(req.url === '/posts' && req.method === 'POST'){
    	req.setEncoding('utf-8')
        
        req.on('data', data => {
        	/**
            * @typedef CreatePostBody
            * @property {string} title
            * @property {string} content
            */
            
            /** @type {CreatePostBody} */
            const body = JSON.parse(data)
            console.log(body)
            
            posts.push({
            	id: body.title.toLowerCase().trim().replace(\/s/g, '_'),
                title: body.title,
                content: body.content
            })
        })
        res.statusCode = 200
        res.end('Creating Post')
    } else {
    	res.statusCode = 404
        res.end('Not found')
    }
    
})

이거에 대한 설명들은 다음 블로그에서 적어야겠다ㅎㅎ

profile
SW로 문제를 해결하려는 열정만 있는 대학생

0개의 댓글