웹 어플리케이션에서 Create 진행해보자.
1. 글생성 UI 만들기
1) Create 버튼 제작
templateHTML 화면상 Create 버튼을 제작한다.
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>
`;
}
Create 버튼이 생성된 것을 확인할 수 있지만, 클릭해보면 Not found가 뜨는 것을 알 수 있다.
2) 글생성 페이지 제작
} 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);
});
}
pathname === '/create' 인 경우를 제작하여 페이지를 제작하였다.
<form action="http://localhost:3000/process_create" method="post">
=> submit 버튼을 누르면 /process_create post를 통해 데이터가 전송된다.(아직 받는것은 하지 않음)
받는 내용으로는 title, description이 있다.
이미지 참조 : Node.js 생활코딩 강의 영상
하지만, 아직 데이터를 받지 못했다.
2) POST 방식으로 전송된 데이터 받기.
먼저 querystring 모듈을 불러온다.
var qs = require('querystring');
이제 pathname === 'create_process'를 추가시키자.
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');
}
qs.parse를 통해 데이터를 파싱할 수 있다.
parse : 구문 분석이라고도하며 문장을 그것을 이루고 있는 구성 성분으로 분해하고 그들 사이의 위계 관계를 분석하여 문장의 구조를 결정하는 것
https://velog.io/@gidskql6671/Nodejs-url%EC%9D%84-%EB%B6%84%EC%84%9D%EC%9D%84-%EB%8F%84%EC%99%80%EC%A3%BC%EB%8A%94-Url-Querystring-%EB%AA%A8%EB%93%88
[Nodejs] url을 분석을 도와주는 Url, Querystring 모듈
url.parse()과 querystring.parse(), querystring.stringify()
velog.io
이를 통해서 아까 Create에서 입력했던 Post를 읽고 해석할 수 있다.
3) 파일 생성과 리다이렉션
마지막으로 파일 생성 및 리다이렉션을 진행해보자.
Nodejs file write 하는 방법을 검색하자. 이번에는 공식문서를 확인
fs.writeFile(`data/${title}`, description, 'utf8', function(err){
response.writeHead(302, {Location: `/?id=${title}`});
response.end();
})
fs.writeFile 메소드를 이용해서 File을 write할 것이다.
추가로 Response.writeHead(302,{Location:`/?id=$[title}`});
이 부분은 페이지 리다이렉션을 추가해줬다.
전체 소스코드
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);