2024년 4월 25일 Node.js-post
route()
- 특정 URL애 대한 미들웨어 및 라우팅 로직을 모듈화하고 그룹화할 수 있음
- 가독성을 향상시키고 유지 보수를 용이하게함
- route() 메소드는 Router 객체를 반환. 해당 객체로 특정 URL 경로에 대한 라우팅을 설정
morgan
- http 요청에 대한 로깅을 수행하기 위한 미들웨어
- express와 함께 사용되며 클라이언트로부터 오는 각각의 요청에 대한 정보를 로깅
- 요청 HTTP 메소드, 발생한 URL, IP주소, 응당상태코드, 데이터의 크기를 알 수 있음
- 옵션: common, short, tiny, dev, combined
문제
posts 라우터 생성 후 post.js에서 아래와 같은 메소드를 테스트해보자
글보기(GET)
글작성(POST)
글수정(PUT)
글삭제(DELETE)
1. post
import express from 'express'
const app = express()
app.use(express.json())
app.post('/posts', (req, res) => {
console.log(req.body)
res.status(201).send('글이 새로 등록되었어요')
})
app.listen(8080)
2. error
import express from 'express'
import fs from 'fs'
import fsAsync from 'fs/promises'
const app = express()
app.use(express.json())
// http://localhost:8080/file1
// 비동기식
app.get('/file1', (req, res) => {
fs.readFile('/file1.txt', (err, data) => {
if(err){
res.sendStatus(404)
}
})
})
// http://localhost:8080/file2
// file2를 읽어 에러가 발생하면 404를 리턴
// 단, file2를 동기식으로 읽음
// 전체적으로 비동기로 읽음
app.get('/file2', (req, res) => {
try{
const data = fs.readFileSync('/file2.txt')
}catch(error){
res.sendStatus(404)
}
})
app.get('file3', (req, res) => {
fsAsync.readFile('/file3.txt')
.catch((error) => {
res.sendStatus(404)
})
})
app.get('/file4', async (req, res) => {
try{
const data = await fsAsync.readFile('/file4.txt')
}catch(error){
res.sendStatus(404)
}
})
app.use((req, res, next) => {
const error = Error('테스트 에러!')
next(error)
})
app.use((error, req, res, next) => {
console.error(error)
res.status(500).json({message:"서버에러"})
})
app.listen(8080)
3. route
import express from 'express'
const app = express()
app
.route('/posts') // 같이 그룹화시킬 수 있음
// get: 조회(select), post: 입력(insert), put: 수정(update), delete: 삭제
.get((req, res) => {
res.status(200).send('GET: /posts')
})
.post((req, res) => {
res.status(200).send('POST: /posts')
})
app
.route('/member/:id')
.put((req, res) => {
res.status(201).send('PUT: /member/:id')
})
.delete((req, res) => {
res.status(200).send('DELETE: /member/:id')
})
app.listen(8080)
posts
member
4. routing
4-1. 라우팅할 폴더를 불러오기
import express from 'express'
// npm i morgan
import morgan from 'morgan'
import userRouter from './routes/user.js'
import postRouter from './routes/post.js'
const app = express()
app.use(express.json())
app.use(morgan('combined'))
// http://localhost8080/users
app.use('/users', userRouter)
app.use('/posts', postRouter)
app.listen(8080)
라우팅할 내용
import express from 'express'
const router = express.Router()
router.use((req, res, next) => {
console.log('posts에 존재하는 미들웨어~!')
next()
})
// http://localhost:8080/posts (GET)
// 글보기
router.get('/', (req, res) => {
res.status(200).send('GET: /posts 글보기')
})
// http://localhost:8080/posts (POST)
// 글작성
router.post('/', (req, res) => {
res.status(201).send('POST: /posts 글작성')
})
// http://localhost:8080/posts (PUT)
// 글수정
router.put('/:id', (req, res) => {
res.status(201).send('PUT: /posts/:id 글수정')
})
// http://localhost:8080/posts (DELETE)
// 글삭제
router.delete('/:id', (req, res) => {
res.status(201).send('DELETE: /posts/:id 글삭제')
})
export default router
방식은 동일해 그 방식에 따라 다른 값을 보여줘 나머지는 호출방식만 달리해서 해주면 될거 같아'
그리고 우리가 이제부터 GitHub라는 버전관리프로그램을 이용해서 버전을 관리해가면서 공부를 해볼꺼야
GitHub: Let’s build from here
GitHub is where over 100 million developers shape the future of software, together. Contribute to the open source community, manage your Git repositories, review code like a pro, track bugs and fea...
github.com
여기 들어가서 회원가입부터 하고 하면되(이미 올려놓고 나중에 글을 적는거라 자세하게 알려주지 못한 점 양해)
이걸 할려면 아마도 Git이라는 프로그램을 이용해서 GitHub랑 연결하는걸로 알고 있어
어쨋든 VS코드를 이용해서 커밋을 하게되면 GitHub에 이렇게 올라온게 보여