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.
화면의 폼에는 보이지 않지만(사용자는 볼 수 없음), 사용자가 입력을 마치면 폼과 함께 서버로 전송되는 요소
(예제)
히든 필드를 사용해 사용자가 사이트에서 로그인하는 정보를 서버로 넘겨줌
<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에서 해당 레코드를 식별하여 업데이트를 쉽게 할 수 있다.
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);
//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를사용하기좋게정리하는도구 : Array, Object
처리하는 코드가 많아지면 서로 연관되는 것들 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();
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);
수정된 데이터를 각 페이지의 파일에 저장할 때, 기존의 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();
})
});
});
}
기존에 있던 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의 형태로 저장하는 방법