생활코딩

Coding Everybody

코스 전체목록

닫기

App - 글삭제 기능 완성

수업소개

글삭제 기능을 완성해봅시다!

 

 

 

강의

 

 

 

 

소스코드

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. Sansol Park
    HTML 폼의 `action` 속성에 사용되는 URL 경로는 상대 경로와 절대 경로 두 가지 형태가 있습니다. 이 경로 설정은 웹 애플리케이션의 URL 구조와 설정에 따라 달라질 수 있습니다. `/delete_process`와 `delete_process`의 차이를 이해하기 위해 상대 경로와 절대 경로의 개념을 설명하겠습니다.

    ### 절대 경로 vs 상대 경로

    - **절대 경로 (Absolute Path)**:
    - 슬래시(`/`)로 시작하며, 웹 서버의 루트 디렉토리를 기준으로 경로를 지정합니다.
    - 예: `/delete_process`는 웹 서버의 루트 디렉토리에 있는 `delete_process` 경로를 가리킵니다.

    - **상대 경로 (Relative Path)**:
    - 슬래시(`/`) 없이 시작하며, 현재 문서의 경로를 기준으로 경로를 지정합니다.
    - 예: `delete_process`는 현재 문서의 경로를 기준으로 `delete_process` 파일이나 디렉토리를 가리킵니다.

    ### 예제 설명

    #### 절대 경로
    ```html
    <form action="/delete_process" method="post">
    ```
    - 여기서 `/delete_process`는 웹 서버의 루트 디렉토리를 기준으로 하므로, `http://example.com/delete_process`로 POST 요청을 보냅니다.
    - 이 방식은 폼이 항상 동일한 서버 내의 루트 경로를 가리키도록 합니다.

    #### 상대 경로
    ```html
    <form action="delete_process" method="post">
    ```
    - 여기서 `delete_process`는 현재 문서의 경로를 기준으로 합니다. 예를 들어, 현재 문서가 `http://example.com/some/path/page.html`에 있다면, 폼은 `http://example.com/some/path/delete_process`로 POST 요청을 보냅니다.

    ### 오류가 발생하는 이유

    오류가 발생하는 이유는 웹 서버의 URL 구조와 설정에 따라 달라집니다.

    1. **웹 서버 설정**:
    - 웹 서버가 루트 디렉토리에 `delete_process` 엔드포인트를 처리하도록 설정되어 있지 않다면, `/delete_process`로 요청을 보낼 때 404 오류가 발생할 수 있습니다.

    2. **현재 경로**:
    - 현재 문서의 경로가 `delete_process` 엔드포인트가 존재하는 경로와 일치하지 않다면, 상대 경로를 사용할 때도 경로를 찾을 수 없어서 오류가 발생할 수 있습니다.

    ### 언제 절대 경로와 상대 경로를 사용해야 할까?

    - **절대 경로**를 사용해야 하는 경우:
    - 폼이 웹 애플리케이션의 특정 위치(루트 디렉토리)에 있는 파일이나 스크립트를 항상 호출해야 할 때.
    - 여러 디렉토리에서 동일한 폼을 사용할 때.

    - **상대 경로**를 사용해야 하는 경우:
    - 폼이 현재 문서와 같은 디렉토리에 있는 파일이나 스크립트를 호출해야 할 때.
    - 폼이 호출하는 경로가 현재 문서의 경로를 기준으로 변경될 때.

    ### 결론

    `<form action="delete_process" method="post">`와 같이 상대 경로를 사용하는 이유는 폼이 현재 문서의 경로를 기준으로 동작하도록 하기 위함입니다. 반면, `<form action="/delete_process" method="post">`는 웹 서버의 루트 디렉토리 경로를 지정합니다. 오류가 발생하는 경우, 웹 서버의 URL 구조와 설정을 확인하고, 폼의 경로가 올바르게 지정되어 있는지 확인해야 합니다.
    대화보기
    • 비전공자
      오후 3:09 2024-05-11
    • 김철흥
      2024.01.12
      완료!
    • BF_Lee
      230705
    • 어흥
      230702
    • Hojun Song
      2023-04-16 10:49
    • 나라세
      <form action="delete_process" method="post">를

      <form action="/delete_process" method="post"> 이런식으로 /를 붙이면 오류가 나던데 여기에는 /를 안붙이는 이유가 있을까요?
    • 백건빈
      22.01.26 완료 화이팅 !
    • 감자
      22.12.04 완료
    • 당당
      2022.10.26
    • 아캔두잇
      20220805 완료
    • 키다리아저씨
      220720 완
    • toonfac
      220714 오후 4시 06분 완료
    • timber3
      감사합니다~
    • kimkk
      CRUD 의 D까지...
    • 초딩 개발자
      2021/12/27
    • 케굴
      2021-12-26
    • pdpd
      21.10.11
    • 졸작완성하자
      21.10.08 완료
    • 20단국
      2021/09/30 완료
    • TODOa
      61 라인에 input type="hidden" 으로 페이지가 생성될 때 넣어둡니다.
      대화보기
      • laqah
        멋집니다!
      • labis98
        20210727 감사합니다.
      • Duke
        2021.07.18
      • 신동민
        처음 생성한 게시글을 update를 하지 않는다면 id값이 생성이 되지 않는거 같은데, delete_process에서는 id값을 어떻게 찾는건가요..?!
      • Jeong Il Haan
        20210422
      • dmsrkfcl15
        글 삭제 기능에서 파일명이"한글 이름"과 같이 한글 사이 공백이 있을 경우 삭제가 이루어지지 않는 문제가 발생했습니다. 이상한 점은 비슷한 구성을 가진 글 수정 기능은 이처럼 파일명이 한글과 공백으로 이루어져 있어도 문제없이 작동한다는 점입니다. 혹시 이와 같은 문제를 해결할 방법을 알고 계신 분 있으신가요?
      • byoonn
        완료
      • 21.02.27
      • chimhyangmoo
        21.02.24
      • jeisyoon
        2021.02.11 App - 글삭제 기능 완료
      • 마아앙
        2021.02.09
      • 뭄수
        완료
      • Noah
        2021.01.06 완료!
      • 마준
        21/01/04 완료
        멍청하게 method를 methos로써서 몇일동안 고생
      • 손민철
        20/12/31 완료
      • 생활둘기
        2020 12 26
      • kkn1125
        20.12.23 완료~!
      • 옹옹
        좀 힘들었는데 막상 완주하니 기쁘네요
      • Juveloper
        좋은 강의 감사합니다 이고잉님 덕분에 CRUD의 기본을 이해할 수 있었어요!
      • 콜라
        20201015 완료
      • Yong Hyun Lee
        완료 201002
      • vampa
        2020.09.10
      • Jenny Song
        CRUD 끝
      • 코딩하는렌즈쟁이
        2020-07-28 (화)
        완료
      • 불스택
        20.07.12 감사합니다 이고잉님
      • Amousk
        좋은 강의 감사합니다.
      • Katherine Roh
        완료 :)
      • 김재익
        완료
      • 김보미
        완료
      버전 관리
      egoing
      현재 버전
      선택 버전
      graphittie 자세히 보기