에러 메시지

next : The term 'next' is not recognized as the name of a cmdlet, function, script file, or operable pro
gram. Check the spelling of the name, or if a path was included, verify that the path is correct and try 
 again.

 

-> next가 없다는 의미 이므로 설치해주면 됨

 

해결 방법

npm install next -g 

Hidden Field란?

화면의 폼에는 보이지 않지만(사용자는 볼 수 없음), 사용자가 입력을 마치면 폼과 함께 서버로 전송되는 요소

 

(예제) 

히든 필드를 사용해 사용자가 사이트에서 로그인하는 정보를 서버로 넘겨줌

<input type = "hidden" value = "사이트를 통한 직접 로그인">
<label> 아이디: <input type = "text" id= "user_id"></label>
<label> 비밀번호: <input type = "password" id= "user_pw"></label>
<input type = "submit" value = "로그인">

실행하면 아래와 같이, hidden filed의 내용은 보이지 않는다.

 

 

 

하지만,, 위의 예제로는 도대체 hidden field를 왜 사용하는지 이해가 되지 않아서 찾아봤는데,,

위의 예제는 hidden field의 내용은 실제로 사용자의 눈에 보이지 않는다는걸 알려주기 위해 나온듯 하고

 

Hidden field에 대해 좀 더 정확히?자세히 말하면

사용자가 입력할 필요가 없는 정보/ 사용자가 몰라도 되는 정보,,이지만 폼 전송과 같이 전송해주어야 하는 정보를 담기 위한 것

어떤 블로그에서는 사용자가 변경해서는 안되는 데이터를 함께 보낼때 사용한다고 정의하였다

예를들면,, 회원가입 시 사용자의 아이피를 받는 경우 히든필드에 넣는 경우도 있고

또,,

어떤 정보를 수정하고자 할때, 데이터베이스 테이블에서 가지고 있는 Primary Key값을 hidden field에 같이 전송하면, 이 primary key값을 통해 DB에서 해당 레코드를 식별하여 업데이트를 쉽게 할 수 있다.

 

 

참고

https://velog.io/@gndan4/HTML-input-typehidden-%EC%96%B8%EC%A0%9C-%EC%93%B0%EC%9D%B4%EB%8A%94-%EA%B1%B8%EA%B9%8C

http://www.homejjang.com/05/HiddenField.php

http://tcpschool.com/html-input-types/hidden

https://codedragon.tistory.com/5438

'Web > HTML\CSS\JavaScript' 카테고리의 다른 글

[JavaScript] Object  (0) 2020.07.31
[HTML] form  (0) 2020.07.30
[JavaScript] Function  (0) 2020.07.25
[JavaScript] Array data type  (0) 2020.07.25
JavaScript 기본 문법과 제어문  (0) 2020.07.21

Module

코드를 작성하는 과정에서 코드의 길이가 길어지면 정리정돈할 필요성이 생김 - 가장 큰 도구 : module

 

nodejs/mpart.js

var M = {
  v:'v',
  f:function(){
    console.log(this.v);
  }
}
 
module.exports = M;

module을 생성하기 위해서 exports 전역 객체를 사용

 

muse.js

var part = require('./mpart.js');
part.f();

module을 불러오기 위해서 require( ) 메소드 사용

 

 

 

'Web > Node.js' 카테고리의 다른 글

[Node.js] object를 통해 template 정리  (0) 2020.07.31
[Node.js] 글 삭제  (0) 2020.07.31
[Node.js] 글 수정  (0) 2020.07.31
[Node.js] 글 생성  (0) 2020.07.31
[Node.js] Package Manger  (0) 2020.07.30

객체지향 프로그래밍 목적 : 코드를 깔끔하게 복잡하지 않게 정리하는것

refactoring : 과거의 코드를 효율적으로 바꾸는 것

 

object를 통해 template 정리

template라는 객체를 만들고 객체 안에서 property를 정의

 

<기존 코드>

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 template = {
  HTML:function(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>
    `; },
    list:function(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;
  }
}

 

위 template를 사용하는 부분 수정

templateList을 template.list로 변경

templateHTML을 template.HTML으로 변경하고 template라고 되어있는 변수를 html로 수정

 

예시( 주석: 기존코드)

/* var list = templateList(filelist);
          var template = templateHTML(title, list,
            `<h2>${title}</h2>${description}`,
            `<a href="/create">create</a>`
          );
          response.writeHead(200);
          response.end(template);
*/
var list = template.list(filelist);
          var html = template.HTML(title, list,
            `<h2>${title}</h2>${description}`,
            `<a href="/create">create</a>`
          );
          response.writeHead(200);
          response.end(html);

 

 

'Web > Node.js' 카테고리의 다른 글

[Node.js] Module 사용  (0) 2020.08.02
[Node.js] 글 삭제  (0) 2020.07.31
[Node.js] 글 수정  (0) 2020.07.31
[Node.js] 글 생성  (0) 2020.07.31
[Node.js] Package Manger  (0) 2020.07.30

Object vs Array

//Array
var members = ['kbs','k0214','1999k'];
console.log(members[1]);    //How to get information

//Object
var roles = {
    'programmer' : 'kbs',
    'designer' : 'k0214',
    'manager' : '1999k'
}
console.log(roles.designer);    How to get information

Array : 각각의 정보를 순서에 따라 정리 (각각의 정보는 고유한 식별자가 존재)

Object : 순서가 없는 정보 저장 (식별자가 숫자가 아닌 이름으로 존재)

  순서 식별자 literal
Array O 숫자 [ ]
Object X 이름 { }

 

object 정의하는 방법 

var 객체이름 = { key : value }

 

Object 에서 key에 대한 value 값을 가져오는 방법

객체이름.key

객체이름[key]

 

loop for Object and Array

//Array
var members = ['kbs','k0214','1999k'];
var i = 0;
while(i<members.length){
    console.log('array loop',members[i]);
    i=i+1;
}

//Object
var roles = {
    'programmer' : 'kbs',
    'designer' : 'k0214',
    'manager' : '1999k'
}
for(var name in roles){
    console.log('object => ', name,'value => ', roles[name]);
}

name : object의 식별자 key  들어오도록 약속되어있음

 

Object Oriented Programming (OOP)

 

Programming을 한다는 것은 크게 두가지로 분류 

1. data

2. data를 처리하는  

data를 사용하기 좋게 정리하는 도구 : ArrayObject 

처리하는 코드가 많아지면 서로 연관되는 것들 grouping하여 구분 : function

 

javascript에서의 function : 처리해야될 일에 대한 정보를 담고 있는 statement + 변수에 넣을 수 있는 value 

var f = function(){
	console.log(1+1);	//statement
}
console.log(f);	//value

 

배열의 원소로서 function 존재 가능

var f = function(){
	console.log(1+1);	//statement
}
console.log(f);	//value
var a =[f];
a[0]();

 

배열과 객체는 모두 서로 연관된 data를 담는 그릇인데, javacript에서는 처리 방법을 grouping하는 함수 조차도 data이기 때문에 배열과 객체에 담을 수 있음 

var f = function(){
	console.log(1+1);
}

var o = {
    func:f
}
o.func();

 

※ function을 배열보다는 객체에 담는 경우가 많음

 

function을 객체에 담을 때

var o = {
    v1 : 'v1',
    v2 : 'v2',
    f1 : function f1(){
    console.log(o.v1);
    },
    f2 : function f2(){
    console.log(o.v2);
    }
}

o.f1();
o.f2();

 

위 코드의 경우, 객체의 이름을 바꾸어보면 함수 안의 내용까지도 바꿔야함을 알 수 있음 

따라서 함수가 객체 안에서 사용될 때, 함수가 자신이 속해있는 객체를 참조할 수 있는 특수한 약속이 필요함

-> this 이용

var o = {
    v1 : 'v1',
    v2 : 'v2',
    f1 : function f1(){
    console.log(this.v1);
    },
    f2 : function f2(){
    console.log(this.v2);
    }
}

o.f1();
o.f2();

 

 

'Web > HTML\CSS\JavaScript' 카테고리의 다른 글

[HTML5] 히든 필드(Hidden field) 사용하는 이유  (0) 2022.03.09
[HTML] form  (0) 2020.07.30
[JavaScript] Function  (0) 2020.07.25
[JavaScript] Array data type  (0) 2020.07.25
JavaScript 기본 문법과 제어문  (0) 2020.07.21

삭제버튼 구현

control 부분에 삭제 할 수 있는 버튼을 추가 

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>
                <a href="/delete?id=${title}">delete</a>`
            );
            response.writeHead(200);
            response.end(template);
          });
        });
      }
    } 

글을 삭제 할 때, 따로 보여줄 페이지가 없기 때문에 링크는 필요하지 않음

따라서 form 태그로 지울 id값을 가지고 delete_process로 넘어가야함

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

 

글 삭제 기능 완성(삭제 요청 처리)

delete_process 

"node.js delete file" - 검색 결과 중 아래 사진 참고

post 방식으로 받아온 id 값으로 지우고자 하는 경로를 fs.unlink()에 넣고 그 다음으로 넘어갈 페이지를 정해줌

fs.unlink( ){ } 안에 response.writeHead(302,넘어갈 페이지) 입력

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

 

<전체 코드>

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

'Web > Node.js' 카테고리의 다른 글

[Node.js] Module 사용  (0) 2020.08.02
[Node.js] object를 통해 template 정리  (0) 2020.07.31
[Node.js] 글 수정  (0) 2020.07.31
[Node.js] 글 생성  (0) 2020.07.31
[Node.js] Package Manger  (0) 2020.07.30

수정링크 생성 (홈페이지에서는 create만 보이고 각 페이지에서는 update가 보이도록 하기 )

temlpateHTML{ } 안에 <a href="/update">update</a> 추가

templateHTML 에서 control을 추가

<a href="/create">create</a> <a href="/update">update</a> 를 ${control}로 수정

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

 

모든 메뉴가 보이는 부분에 a 태그로 링크를 설정한다. 

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>`
            );
            response.writeHead(200);
            response.end(template);
          });
        });
      }

 

수정할 정보 전송 ( update를 클릭했을 때 보여지는 화면 생성)

form 과 read 기능 필요

기존의 내용을 가져올 수 있도록 fs.readFile()을 통해 데이터를 가져오고 이 데이터를 input의 value 로 표시되게끔 입력

id 기존 값, title 바뀐값

hidden 속성 : 사용자에게 정보가 보이지 않기 때문에 데이터를 보낼 때 유용하게 사용 

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

 

수정된 내용 저장

수정된 데이터를 각 페이지의 파일에 저장할 때, 기존의 id 값을 바뀐 title 값으로 수정하기 위해 fs.rename( ) 사용

"node.js file rename" - 검색 결과 아래 사진 참고 

fs.rename(이전 경로,새로운 경로,callback 함수){ } 안에 fs.writeFile(새로운 경로, 페이지 내용, encoding, callback함수)로 파일을 수정하고 저장

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

'Web > Node.js' 카테고리의 다른 글

[Node.js] object를 통해 template 정리  (0) 2020.07.31
[Node.js] 글 삭제  (0) 2020.07.31
[Node.js] 글 생성  (0) 2020.07.31
[Node.js] Package Manger  (0) 2020.07.30
[Node.js] synchronous(동기적) asynchronous(비동기적)  (0) 2020.07.27

UI 만들기

기존에 있던 if(pathname === '/') 이외에 /가 아닌 create일 때의 조건문 생성

해당 조건문 내용 : 글을 작성할 수 있는 페이지 작성 , 기존의 template에 html의 form 태그 추가 

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/process_create" 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);
      });

 

Post 방식으로 전송된 데이터 받기 

 

"node.js post data" 검색 후 나온 결과 - 아래 사진 참고 

웹브라우저가 post방식으로 데이터를 전송할 데이터가 엄청나게 많으면 컴퓨터에 무리가 가는 문제가 생김 -> node.js는 post방식으로 전송되는 데이터가 많을 경우를 대비해서 특정한 양의 데이터를 서버에서 수신할 때마다 서버는 callback 함수를 호출하도록 약속되어있음 

form의 post 방식으로 가져온 데이터를 /create_process 페이지로 넘어가면서 확인하고자 할 때, createServer의 인자인 request로 데이터를 요청하고, 받은 데이터를 query string 모듈의 parse로 객체화 하여 데이터를 콘솔에 출력할 수 있음

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

 

파일 생성

post 방식으로 전송된 데이터를 data directory안에 file의 형태로 저장하는 방법

"node.js file write"

https://nodejs.org/dist/latest-v12.x/docs/api/fs.html#fs_fs_writefile_file_data_options_callback

 

File system | Node.js v12.18.3 Documentation

 

nodejs.org

위에서 작성한 request.on('end',function(){ } 안에 다음의 코드를 작성한다. 

fs.writeFile(`data/${title}`, description, 'utf8', function(err){
            response.writeHead(200);
            response.end('success');
          })

 

리다이렉션

콜백함수 안에서 작성한 페이지를 확인하기 위해 그 페이지로 넘어가는 것

"node.js redirection"  - 검색 후 나온 결과 아래 사진 참고

위에서 작성한 fs.writeFile(){ } 안의 response.writeHead( ) 부분을 아래와 같이 수정

fs.writeFile(`data/${title}`, description, 'utf8', function(err){
            response.writeHead(302, {Location: `/?id=${title}`});
            response.end();
          })

+ Recent posts