Back-end/Node.js

[Node.js] POST방식으로 데이터 전송하고 받기, 파일 생성, 리다이렉션

poppy 2020. 12. 23. 13:54
반응형

soohyun6879.tistory.com/65

 

[Node.js] 파일 목록 알아내기 / 반목문과 함수를 사용하여 중복 제거하기

파일 목록 알아내기 var testFolder = './data'; //파일위치 var fs = require('fs'); fs.readdir(testFolder, function(error, filelist){ console.log(filelist); }) 파일 목록을 알아내기 위해서는 fs모듈을..

soohyun6879.tistory.com

이전 포스팅에 이어서 POST방식으로 데이터를 입력 받고, 받은 데이터로 파일을 생성하고, 리다이렉션을 해보겠습니다.

 

 

데이터 전송하고 받기

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>
  `;
}

데이터를 입력받을 수 있는 링크를 만들어 줍니다.

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);
      });
    }

데이터를 입력받는 링크를 "/cereate" 라고 주었으므로 pathname === '/create' 일 때를 정의해줍니다. Home화면과 똑같이 화면을 만들어주고, 데이터를 입력받을 수 있게 입력칸을 만들어 줍니다.

데이터를 입력받아 보내기 위해서는 <form>을 사용해야 합니다.  <form> 의 action은 데이터를 보낼 링크를 의미하고, method는 데이터를 전송할 방식을 의미합니다. GET방식은 링크에 데이터의 정보가 보이기 때문에 데이터 유출 위험이 있으므로 POST방식을 선택하는 것이 좋습니다. placeholder는 입력칸에 어떤 정보를 입력받을지에 대한 힌트를 주는 것 입니다. "submit(제출)" 버튼을 누르면 데이터가 전송됩니다.

var qs = require('querystring');

else if(pathname === '/create_process'){
      var body = ''; //받을 데이터
      request.on('data', function(data){ //데이터를 수신받을 때마다 data콜백 실행
          body = body + data;
      });
      request.on('end', function(){ // 더 이상 들어올 데이터가 없을 때 end콜백 실행
          var post = qs.parse(body); 
          var title = post.title;
          var description = post.description;
      });

전송된 데이터를 받는 링크를 "/create_process"로 주었으므로 pathname === '/create_process'를 정의해줍니다. 

데이터를 받을 때는 request.on( )을 사용합니다. request.on('data'function(data){ ... }) 은 데이터를 수신받을 때마다 이 함수가 콜백되어 실행됩니다. 데이터의 양이 많을 수 있으므로 한 번에 데이터를 받는 것이 아니고 데이터의 조각들을 받을 때마다 data 콜백이 실행되어 데이터를 계속 추가해줍니다. request.on('end'function(){ ... }) 은 더 이상 들어올 데이터가 없을 때 이 함수가 콜백되어 실행됩니다. 이 콜백이 실행되면 받은 모든 데이터를 querystring 모듈을 사용하여 정보를 가져옵니다. post 데이터에 post 정보가 있습니다. post.title은 받은 정보의 title을 가져오는 것이고, post.description은 받은 정보의 description을 가져오는 것 입니다. 

 

파일 생성 & 리다이렉션

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();
          })
      });

위의 코드에 파일 생성하는 부분과 리다이렉션하는 부분을 추가하겠습니다.

writeFile( )을 사용하여 파일을 생성하겠습니다. `data/${title}` 은 파일위치 및 파일 이름을 설정하는 것입니다. data 폴더 아래에 title의 이름을 가진 파일을 만들도록 하였습니다. description은 파일의 내용을 설정하는 것 입니다.

리다이렉션은 말 그대로 출력의 방향을 바꾸는 것으로 원하는 화면으로 출력을 바꾸어주는 것을 말합니다.

response.writeHead(302, {Location: `/?id=${title}`}); 로 리다이렉션 해주는데 첫번째 인자는 리다이렉션의 코드 번호이고, 두번째 인자는 출력 url입니다. 

 

실행 화면입니다.

 

전체 코드입니다.

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;
          fs.writeFile(`data/${title}`, description, 'utf8', function(err){
            response.writeHead(302, {Location: `/?id=${title}`});
            response.end();
          })
      });
    } else {
      response.writeHead(404);
      response.end('Not found');
    }
});
app.listen(3000);

main.js
0.00MB

반응형