생활코딩

Coding Everybody

App - 글삭제 - 삭제버튼 구현

토픽 생활코딩 > WEB > WEB2 - Node.js

수업소개

삭제 작업을 하기 위해서는 삭제 버튼이 있어야 합니다. 이 때 링크를 사용하는 안됩니다. 링크 대신 form을 이용해서 삭제 버튼을 만드는 방법을 살펴보겠습니다. 

 

 

 

강의

 

 

 

소스코드

main.js (변경사항)

var http = require('http');
var fs = require('fs');
var url = require('url');
var qs = require('querystring');

function templateHTML(title, list, body, control){
  return `
  <!doctype html>
  <html>
  <head>
    <title>WEB1 - ${title}</title>
    <meta charset="utf-8">
  </head>
  <body>
    <h1><a href="/">WEB</a></h1>
    ${list}
    ${control}
    ${body}
  </body>
  </html>
  `;
}
function templateList(filelist){
  var list = '<ul>';
  var i = 0;
  while(i < filelist.length){
    list = list + `<li><a href="/?id=${filelist[i]}">${filelist[i]}</a></li>`;
    i = i + 1;
  }
  list = list+'</ul>';
  return list;
}

var app = http.createServer(function(request,response){
    var _url = request.url;
    var queryData = url.parse(_url, true).query;
    var pathname = url.parse(_url, true).pathname;
    if(pathname === '/'){
      if(queryData.id === undefined){
        fs.readdir('./data', function(error, filelist){
          var title = 'Welcome';
          var description = 'Hello, Node.js';
          var list = templateList(filelist);
          var template = templateHTML(title, list,
            `<h2>${title}</h2>${description}`,
            `<a href="/create">create</a>`
          );
          response.writeHead(200);
          response.end(template);
        });
      } else {
        fs.readdir('./data', function(error, filelist){
          fs.readFile(`data/${queryData.id}`, 'utf8', function(err, description){
            var title = queryData.id;
            var list = templateList(filelist);
            var template = templateHTML(title, list,
              `<h2>${title}</h2>${description}`,
              ` <a href="/create">create</a>
                <a href="/update?id=${title}">update</a>
                <form action="delete_process" method="post">
                  <input type="hidden" name="id" value="${title}">
                  <input type="submit" value="delete">
                </form>`
            );
            response.writeHead(200);
            response.end(template);
          });
        });
      }
    } else if(pathname === '/create'){
      fs.readdir('./data', function(error, filelist){
        var title = 'WEB - create';
        var list = templateList(filelist);
        var template = templateHTML(title, list, `
          <form action="/create_process" method="post">
            <p><input type="text" name="title" placeholder="title"></p>
            <p>
              <textarea name="description" placeholder="description"></textarea>
            </p>
            <p>
              <input type="submit">
            </p>
          </form>
        `, '');
        response.writeHead(200);
        response.end(template);
      });
    } else if(pathname === '/create_process'){
      var body = '';
      request.on('data', function(data){
          body = body + data;
      });
      request.on('end', function(){
          var post = qs.parse(body);
          var title = post.title;
          var description = post.description;
          fs.writeFile(`data/${title}`, description, 'utf8', function(err){
            response.writeHead(302, {Location: `/?id=${title}`});
            response.end();
          })
      });
    } else if(pathname === '/update'){
      fs.readdir('./data', function(error, filelist){
        fs.readFile(`data/${queryData.id}`, 'utf8', function(err, description){
          var title = queryData.id;
          var list = templateList(filelist);
          var template = templateHTML(title, list,
            `
            <form action="/update_process" method="post">
              <input type="hidden" name="id" value="${title}">
              <p><input type="text" name="title" placeholder="title" value="${title}"></p>
              <p>
                <textarea name="description" placeholder="description">${description}</textarea>
              </p>
              <p>
                <input type="submit">
              </p>
            </form>
            `,
            `<a href="/create">create</a> <a href="/update?id=${title}">update</a>`
          );
          response.writeHead(200);
          response.end(template);
        });
      });
    } else if(pathname === '/update_process'){
      var body = '';
      request.on('data', function(data){
          body = body + data;
      });
      request.on('end', function(){
          var post = qs.parse(body);
          var id = post.id;
          var title = post.title;
          var description = post.description;
          fs.rename(`data/${id}`, `data/${title}`, function(error){
            fs.writeFile(`data/${title}`, description, 'utf8', function(err){
              response.writeHead(302, {Location: `/?id=${title}`});
              response.end();
            })
          });
      });
    } else if(pathname === '/delete_process'){
      var body = '';
      request.on('data', function(data){
          body = body + data;
      });
      request.on('end', function(){
          var post = qs.parse(body);
          var id = post.id;
          fs.unlink(`data/${id}`, function(error){
            response.writeHead(302, {Location: `/`});
            response.end();
          })
      });
    } else {
      response.writeHead(404);
      response.end('Not found');
    }
});
app.listen(3000);

 

댓글

댓글 본문
  1. 비전공자
    오후 3:06 2024-05-11
  2. 김철흥
    2024.01.12
    완료!
  3. BF_Lee
    230705
  4. 어흥
    230702
  5. Hojun Song
    2023-04-16 10:35
  6. 감자
    22.12.04 완료
  7. 당당
    2022.10.26
  8. Sukjoon Lee
    20220812
  9. 아캔두잇
    20220805 완료
  10. 키다리아저씨
    220720 완
  11. toonfac
    220714 오후 4시 04분 완료
  12. 화려하게간다
    화긴~~~~
  13. kimkk
    Do not implement delete function with anchor tag.
    Very dangerous.

    Use input tag of type="submit" (button) within the form tag
  14. 초딩 개발자
    2021/12/26
  15. 케굴
    2021-12-26
  16. 일억개
    가즈아!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  17. pdpd
    211011
  18. 졸작완성하자
    211008 완료
  19. labis98
    20210727 완료~~~~
  20. Duke
    2021.07.18
  21. Jeong Il Haan
    20210421
  22. byoonn
    완료
  23. 21.02.27
  24. chimhyangmoo
    21.02.24
  25. jeisyoon
    2021.02.11 App - 글삭제 - 삭제버튼 구현 완료
  26. 마아앙
    2021.02.09
  27. hanel_
    21.2.5
  28. 뭄수
    완료
  29. ohhigo
    21/1/24 감사합니다.
  30. Noah
    2021.01.06 완료
  31. 손민철
    20/12/31 완료
  32. kkn1125
    20.12.23 완료~!
  33. 콜라
    20201015 완료
  34. Yong Hyun Lee
    완료 201002
  35. vampa
    2020.09.10
  36. 코딩하는렌즈쟁이
    2020-07-28 (화)
    완료
  37. 불스택
    20.07.12 감사합니다
  38. 영호팍
    완료오~~~!
  39. Amousk
    좋은 강의 감사합니다.
  40. Katherine Roh
    완료 :)
  41. 김재익
    완료
  42. 김보미
    완료
  43. 바다의왕자
    완료
  44. bomnie
    삭제버튼을 링크로 만들면 특정 페이지 주소로 이동하기 때문에 form으로 만들어서 post 방식으로 보내야 한다.
  45. 준바이
    감사합니다
  46. 심여수
    감사합니다
  47. 03.11 완료
  48. eddylee123456
    복습
  49. eddylee123456
    완료
  50. 스티븐잡숴
    완료