[Node.js]

[Node.js] 서버로 데이터 보내기, 게시글 삭제 만들기

VaIice 2024. 7. 16. 17:03

 1. 주소창, <a>, <form>

 사용하면 새로고침 

 

 2. ajax - fetch

 새로고침 없이 API 요청 가능 

 body 안에 전송 

 

 3. URL 파라미터 

 
     fetch(`/delete/<%-post._id%>`, {
 

 

 4. query string 

 
     fetch(`/delete?id=<%-post._id%>`, {
      method: 'DELETE',
      headers : {
        'Content-Type' : 'application/json'
      }
 

 

 ?변수=값&변수=값 

 서버에서 request.query로 사용 

 

 5. 삭제 코드

// server.js
 
app.delete('/delete/:id', async (request, response) => {
  try {
    await db.collection('main').deleteOne({ _id: new ObjectId(request.params.id) });
      response.sendStatus(204);
  }
  catch {
    response.redirect('/')
  }
})

 

 POST는 redirect가 가능하지만, DELETE는 안 된다고 한다. 

 

// detail.ejs

function deletePost() {
     fetch(`/delete/<%-post._id%>`, {
      method: 'DELETE',
      headers : {
        'Content-Type' : 'application/json'
      }
     })
     .then(response => {
      if (response.ok) {
        window.location.href = '/'
      }
     })
  }  
 

 

 때문에 JS에서 직접 주소를 옮겨주는 코드를 작성해야 한다.