Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- updatemany
- expess
- deserializeUser
- git vscode
- typescript #class #extends #public #private #protected #static
- typescript #react #jsx #component #usestate
- insertone
- Passport
- connect-mongo
- sendFile
- mongodb 입출력
- typescript #import #export #*
- updateone
- github#로컬저장소#원격저장소
- TypeScript #문법
- git#github#init#add#commit#restore#log#staging area#repository#git사용법
- GitHub Actions
- e.target
- serializeUser
- CSS
- Promise #async #await #try #catch
- 정적 페이지
- typescript #unknown
- __dirname
- ejs 문법
- typescript #constructor #class #public #private
- github#githubpages#gh-pages#deploy
- typescript #class #constructor #public #private #static #extends #protected #typeof #in #instanceof #never
- react#로스트아크#mbti#테스트
- github#githubpages#빈화면#basename
Archives
- Today
- Total
VaIice의 이야기
[Node.js] 글쓰기 만들기 본문
1. 폼 만들기
<form class="form-box" action="/add" method="POST">
<h4>글쓰기</h4>
<input type="text" name="title" required>
<input name="content" required>
<button type="submit">전송</button>
</form>
button을 누르면 /new 경로로 이동 후 POST 요청서버로 전달하고 싶으면 name="" 속성 열기
2. 유저 데이터 출력
// server.js
app.use(express.json())
app.use(express.urlencoded({extended:true}))
3. POST
// server.js
app.post('/add', async (request, response) => {
// document를 만들고, 데이터 저장
await db.collection('main').insertOne(request.body)
let result = await db.collection('main').find().toArray()
response.redirect('/')
})
request.body
POST로 보낸 데이터 확인 가능
redirect
URL 이동
유저가 POST 요청 시 코드 실행
4. 검열
// server.js
app.post('/add', async (request, response) => {
// 검열
if (!request.body.title) {
response.send('제목을 입력하세요.');
} else {
await db.collection('main').insertOne(request.body)
let result = await db.collection('main').find().toArray()
response.redirect('/')
}
})
Q. 프론트엔드에서 검열하면 안 되나?
A. 안 된다. 프론트엔드 코드는 위조 가능
5. try { } catch { }
// server.js
app.post('/add', async (request, response) => {
try {
// document를 만들고, 데이터 저장
if (!request.body.title) {
response.send('제목 입력 안 해?');
} else {
await db.collection('main').insertOne(request.body)
let result = await db.collection('main').find().toArray()
response.redirect('/')
}
}
catch {
// 에러 메세지 출력
console.log(e)
response.status(500).send('서버 에러')
}
})
try를 실행하고, 문제가 생기면 catch
status(500) 에러 코드 전송
요약
코드 짤 땐 기능 설명부터
<form>으로 POST 요청 가능
서버에서 request.body 확인 가능
DB에 document 생성은 .insertOne(데이터)
.redirect URL 이동
사용자가 보낸 데이터 검사 if else
try catch 에러 처리
'[Node.js]' 카테고리의 다른 글
[Node.js] 페이지 기능 만들기 (0) | 2024.07.16 |
---|---|
[Node.js] 서버로 데이터 보내기, 게시글 삭제 만들기 (2) | 2024.07.16 |
[Node.js] 게시글 수정 만들기 (0) | 2024.07.15 |
[Node.js] 상세 페이지 만들기 (0) | 2024.07.14 |
[Node.js] API method, URL (0) | 2024.07.10 |