순서!
1. 입력받은 데이터를 보내줄 form태그를 만든다!
2. form태그의 action에 대한 api를 서버쪽에서 만들어준다.
1. form태그 만들기
웹에서 데이터를 DB로 쏴주고 싶으면 form태그를 이용해서 POST방식으로 쏴주면 됩니다!
<form class="form-box" action="/add" method="POST">
<h4>글쓰기</h4>
<input name="title">
<input name="content">
<button type="submit">전송</button>
</form>
전송 버튼을 눌렀을때, POST방식으로 action="/add"가 되므로
"/add"가 되었을 때 DB처리를 해주면 됩니다.
2. 서버파일에서 액션에 대한 api를 작성해줍니다!
app.post('/add', async (요청, 응답)=>{
console.log(요청.body)
await db.collection('post').insertOne({title : 요청.body.title, content: 요청.body.content})
응답.redirect('/list')
})
form으로 받은 데이터는 요청.body에 모두 담겨있습니다!
요청.body 안의 데이터를 insertOne() 함수로 데이터 추가를 해줍니다.
( await을 사용하려면 async (요청, 응답) 사용하기 )
+ 추가로
예외처리1) title이 비어있을 때 경고창 띄워주기!
app.post('/add', async (요청, 응답)=>{
console.log(요청.body)
if(요청.body.title = ""){
응답.send("<script>alert('아이디를 입력해주세요');window.location.replace('/write')</script>")
}else{
await db.collection('post').insertOne({title : 요청.body.title, content: 요청.body.content})
응답.redirect('/list')
}
})
( 응답.send() 안에 스크립트 문법을 사용해서 경고창을 띄울수도 있습니다! )
++ 추가추가로
예외처리2) DB처리시 에러가 났을 때 특정 코드 실행하기!( try catch문법을 사용 )
try{
if(요청.body.title ==''){
응답.send("<script>alert('아이디를 입력해주세요');window.location.replace('/write')</script>")
}else {
await db.collection('post').insertOne({title : 요청.body.title, content: 요청.body.content})
응답.redirect('/list')
}
} catch(e){
console.log(e)
응답.status(500).send('서버에러남.')
}
'Node.js' 카테고리의 다른 글
수정하기2 ( 참고 ) (2) | 2023.12.06 |
---|---|
수정하기 (0) | 2023.12.04 |
EJS 문법 (0) | 2023.11.28 |
웹페이지에 DB데이터 출력하기 (0) | 2023.11.27 |
서버와 MongoDB 연결하기 (2) | 2023.11.27 |