생활코딩

Coding Everybody

코스 전체목록

닫기

App - POST 방식으로 전송된 데이터 받기

수업소개

POST 방식으로 전송된 데이터를 받아서 파일로 저장하는 방법에 대해서 알아보겠습니다. 

 

 

강의

 

 

소스코드

main.js (변경사항)

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

function templateHTML(title, list, body){
  return `
  <!doctype html>
  <html>
  <head>
    <title>WEB1 - ${title}</title>
    <meta charset="utf-8">
  </head>
  <body>
    <h1><a href="/">WEB</a></h1>
    ${list}
    <a href="/create">create</a>
    ${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}`);
          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}`);
            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="http://localhost:3000/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
      });
      response.writeHead(200);
      response.end('success');
    } else {
      response.writeHead(404);
      response.end('Not found');
    }



});
app.listen(3000);

 

댓글

댓글 본문
  1. 김철흥
    2024.01.12
    완료!
  2. Hoon Ko
    20231017
  3. 23.9.24
  4. BF_Lee
    23.07.04
  5. 어흥
    230702
  6. Hojun Song
    2023-04-15 18:56
  7. Nayeong Koo
    23.03.17

    <form action="해당 주소" method="post">를 이용해 POST 방식으로 해당 주소에 데이터를 보냈을 때
    해당 주소에서 데이터를 받는 방법

    request.on을 두 번 사용하여
    데이터가 전송 될 때는 첫 번째 request.on 콜백함수로 데이터를 잘게 조개서 body 변수에 저장 후
    데이터 전송이 멈추면 두 번째 request.on에서 qs.parse로 객체 형태 데이터를 뽑아낸 후 key값으로 데이터에 접근한다.
  8. 감자
    22.12.02 완료
  9. 당당
    2022.10.24
  10. i_am_es
    2022-08-10
  11. 아캔두잇
    20220805 완료
  12. 키다리아저씨
    220719 완
  13. toonfac
    220714 오후 3시 36분 완료
  14. xogk1128
    220713 완료
  15. kimkk
    request.on event for 'data' and 'end' with callback function
    querystring module can parse the requested message from web browser to web server
  16. 케굴
    2021-12-26
  17. 초딩 개발자
    2021/12/12
  18. 일억개
    저도 qs 글자에 줄이 그어져 있길래 자세히 봤더니
    VSC 편집기에서 querystring 말고 URLSearchParams를 사용하라더군요
    그래서 아래와 같이 바꿔봤습니다.

    var post = qs.parse(body);
    var title = post.title;
    var description = post.description;

    var title = new URLSearchParams(body).get('title');
    var description = new URLSearchParams(body).get('description');

    아주 잘 동작합니다.
    'new'는 Javascript 문법인 듯

    참고 사이트
    https://developer.mozilla.org......ams

    (https://webisfree.com) 자바스크립트에서 URL 쿼리스트링(Query String) 쉽게 가져오는 방법

    https://www.w3schools.com......asp
    대화보기
    • 일억개
      가슴이 설렌다
    • BlitzcrankNautilusSeraphine
      저도 똑같습니다 그치만 정상적으로 실습은 가능하니 당장은 생각안해도 될거같습니다.
      대화보기
      • chloekim66
        쿼리스트링이 요새 사용이안되는건가요 ? 제가 잘못쓴건가요 줄이 쭉 가잇네요
      • pdpd
        21.10.09
      • 졸작완성하자
        211007 완료
      • 별거
        점점 어려워지는데 점점 흥미진진해지네요!
      • 쿨러는녹투아
        20210913
      • 승뇽뇽
        ㅇㄹ
      • labis98
        20210726 good!
      • Duke
        2021.07.18
      • 해밀턴
        210707
      • aminora
        안되는 인원들은 복붙해서 그렇습니다.

        form.html에서 가장 윗줄을

        <form action="http://localhost:3000/create_process" method="post">

        로 수정하세요
      • Jeong Il Haan
        20210421
      • byoonn
        완료
      • 21.02.27
      • chimhyangmoo
        21.02.23
      • 마아앙
        2021.02.09
      • jeisyoon
        2021.02.09 App - Post 방식으로 전송된 데이터 받기 완료.
        휴 ~~~ 오타로 1시간 허비 진땀 나내요 .
      • 나그네
        감사합니다.~ 완료
        var description = post.description;
      • 뭄수
        완료
      • ohhigo
        21/1/24 post 데이터 받기
        감사합니다.
      • Noah
        2021.01.05 완료
      • 손민철
        20/12/30 완료
      • 생활둘기
        2020 12 26
      • kkn1125
        20.12.22 완료~!
      • 옹옹
        20201124
      • 콜라
        20201015 완료
      • Yong Hyun Lee
        완료 201002
      • 박병진
        완료
      • vampa
        2020.09.10
      • 마준
        <form action="http://localhost:3000/create_process" method="post">
        멍청했습니다.
        http://인데 http//로 썼네요!
      • 마준
        두번째 else if에서
        else if(pathname ==='/create_process'){
        response.writeHead(200);
        response.end('sucess');
        이부분이 동작하지 않는거같아서 맨마지막 else 부분을
        else{
        response.writeHead(404);
        response.end('not found');
        console.log(pathname);
        }
        이렇게 처리해보았습니다.
        그런데 콘솔에서 pathname값이
        /http//localhost:3000/create_process으로 뜨는건 어떻게해야할까요?

        위에 폼액션을
        <form action="http//localhost:3000/create_process" method="post">
        이렇게 썼는데 뭔가 틀린게있나요?
      graphittie 자세히 보기