• 로그인
  • 장바구니에 상품이 없습니다.

home2 게시판 Node.js, Express 게시판 AJAX로 삭제 요청하기 2에서 질문입니다.

AJAX로 삭제 요청하기 2에서 질문입니다.

10 글 보임 - 1 에서 10 까지 (총 13 중에서)
  • 글쓴이
  • #47670

    코딩이
    참가자
    const express = require("express");
    const app = express();
    const bodyParser = require("body-parser");
    app.use(bodyParser.urlencoded({ extended: true }));
    const MongoClient = require("mongodb").MongoClient;
    app.set("view engine", "ejs");
    var db;
    MongoClient.connect(
      "mongodb+srv://gihwan:@atlascluster.u961rpo.mongodb.net/?retryWrites=true&w=majority",
      function (err, client) {
        if (err) return console.log(err);
        db = client.db("todoapp");
        app.listen(8080, function () {
          console.log("listening on 8080");
        });
      }
    );
    app.get("/pet", function (req, res) {
      res.send("반갑습니다");
    });
    app.get("/beauty", function (req, res) {
      res.send("고맙습니다");
    });
    app.get("/", function (req, res) {
      res.sendFile(__dirname + "/write.html");
    });
    app.get("/index", function (req, res) {
      res.sendFile(__dirname + "/index.html");
    });
    app.post("/add", function (요청, 응답) {
      응답.send("전송완료");
      db.collection("counter").findOne(
        { name: "게시물갯수" },
        function (에러, 결과) {
          var 총게시물갯수 = 결과.totalPost;
          db.collection("post").insertOne(
            { _id: 총게시물갯수 + 1, 제목: 요청.body.title, 날짜: 요청.body.date },
            function () {
              console.log("저장완료");
              db.collection("counter").updateOne(
                { name: "게시물갯수" },
                { $inc: { totalPost: 1 } },
                function (에러, 결과) {
                  if (에러) {
                    return console.log(에러);
                  }
                }
              );
            }
          );
        }
      );
    });
    app.get("/list", function (요청, 응답) {
      db.collection("post")
        .find()
        .toArray(function (에러, 결과) {
          console.log(결과);
          응답.render("list.ejs", { posts: 결과 });
        });
    });
    app.delete("/delete", function (요청, 응답) {
      요청.body._id = parseInt(요청.body._id);
      db.collection("post").deleteOne(요청.body, function (에러, 결과) {
        console.log("삭제완료");
      });
      응답.send("삭제완료");
    });
    server.js 파일이고요
    
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <!-- Required meta tags -->
        <meta charset="utf-8" />
        <meta
          name="viewport"
          content="width=device-width, initial-scale=1, shrink-to-fit=no"
        />
        <!-- Bootstrap CSS -->
        <link
          rel="stylesheet"
          href="https://cdn.jsdelivr.net/npm/bootstrap@4.4.1/dist/css/bootstrap.min.css"
          integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh"
          crossorigin="anonymous"
        />
        <title>Hello, world!</title>
      </head>
      <body>
        <h1 class="ml-2 my-3">오늘 할 일</h1>
        <% for (var i=0; i< posts.length ; i++){ %>
        <ul class="list-group">
          <li class="list-group-item">
            <h4>할일 제목 : <%= posts[i].제목 %></h4>
            <h5>할일 제목 : <%= posts[i].날짜 %></h5>
            <button>삭제</button>
         

          <% } %>    

        <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
        <script>
          $.ajax({
            method: "DELETE",
            url: "/delete",
            data: { _id: 1 },
          }).done(function (결과) {
            console.log("delete success");
          });
        </script>
        <!-- Optional JavaScript -->
        <!-- jQuery first, then Popper.js, then Bootstrap JS -->
        <script
          src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"
          integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
          crossorigin="anonymous"
        ></script>
        <script
          src="https://cdn.jsdelivr.net/npm/bootstrap@4.4.1/dist/js/bootstrap.min.js"
          integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6"
          crossorigin="anonymous"
        ></script>
      </body>
    </html>
    list.ejs 파일입니다.
    
    삭제가 안되고 cannot get /delete 라고 화면이 뜹니다 해결 방법을 좀 알려주세요
    
    
    #47676

    codingapple
    키 마스터
    /delete 안만들어놨다는 에러같은데 파일저장했나 확인합시다
    글에 db계정 비번도 함께 올리시면 안됩니다
    #47715

    코딩이
    참가자
    감사합니다
    #47716

    코딩이
    참가자
    그래도 안됩니다 ㅠㅠ
    #47721

    코딩이
    참가자
    app.delete 가 아니라 app.get을 하니까 지워지는데 app.delete로 해야 되는거죠?
    #47722

    코딩이
    참가자
    다시 하니까 지워졌다가 또 안지워집니다
    #47733

    codingapple
    키 마스터
    list.ejs 방문할 때 마다 /delete로 delete 요청보내라고 코드짠거같은데
    크롬콘솔창 등에 에러같은건 안뜨나요
    #47747

    코딩이
    참가자
    따로 에러가 안나서 그냥 cannot get/delete 만 뜹니다
    
    Get으로 받으면 server.js 는 작동이 되는데
    
    list.ejs에서 뭔가 문제가 있는 거 같은데 모르겠어요
    
    
    
    
    #47788

    codingapple
    키 마스터
    버튼누르면 delete 요청하라고 강의들으면서 더 코드짜봅시다
    #47790

    코딩이
    참가자
    참고하겠습니다
10 글 보임 - 1 에서 10 까지 (총 13 중에서)
  • 답변은 로그인 후 가능합니다.

About

현재 월 700명 신규수강중입니다.

  (09:00~20:00) 빠른 상담은 카톡 플러스친구 코딩애플 (링크)
  admin@codingapple.com
  이용약관, 개인정보처리방침
ⓒ Codingapple, 강의 예제, 영상 복제 금지
top

© Codingapple, All rights reserved. 슈퍼로켓 에듀케이션 / 서울특별시 강동구 고덕로 19길 30 / 사업자등록번호 : 212-26-14752 온라인 교육학원업 / 통신판매업신고번호 : 제 2017-서울강동-0002 호 / 개인정보관리자 : 박종흠