* 해당 포스터는 생활코딩 강의를 정리한 내용입니다.
[ post 방식으로 전송된 데이터를 데이터 디렉토리 안에 파일의 형태로 저장하기 ]
fs.writeFile(`data/${title}`, description, 'utf8', function(err){
//err은 에러가 있을 경우에 에러를 처리하는 방법
response.writeHead(200);
response.end('success');
});
callback 함수를 실행이 된다라는 것은 '파일에 저장이 끝났다'라는 의미
main.js를 실행했을 때 data 폴더에 새로운 파일이 생성되어 있다면 성공
[ 사용자를 방금 생성한 파일을 보는 뷰페이지로 보내기 ]
localhost:3000/?id=nodejs 라는 주소로 보내면 사용자가 자신이 입력한 title, description 을 확인 가능하다.
리다이렉션 : 사용자가 접속한 페이지에서 어떠한 처리를 한 다음에 다시 사용자를 다른 페이지로 옮겨버리기
response.writeHead(301, {Location : --- });
/* 301 : 사용자를 다른 주소로 보내기는 하지만 사용자가
접속한 페이지에서는 영원히 Location으로 지정해준 페이지로만 가게 되어있음. */
//writeHead(200) : 200은 성공했다는 의미
response.writeHead(302)
//302는 페이지를 다른 페이지로 리다이렉션 시키기
데이터를 입력해서 submit을 하면 파일이 data 디렉토리에 생성되면서 그 데이터의 페이지로 이동한다.
var http = require('http');
var fs = require('fs');
var url = require('url');
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 += 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;
var qs = require('querystring')
//qs는 querystring이라는 NodeJS가 가지고 있는 모듈을 가져온다.
if( pathname === '/'){
if( queryData.id === undefined ){ //home
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>
<p>${description}</p>`);
response.writeHead(200);
response.end(template);
})
} else {
fs.readdir('./data', function(error, filelist) {
fs.readFile(`data/${queryData.id}`, 'utf8', function(err,description){
var list = templateList(filelist);
var title = queryData.id
var template = templateHTML(title,list,`<h2>${title}</h2>
<p>${description}</p>`);;
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-> 사용자가 요청한 정보안에는 post 정보가 있음
request.on('data',function(data){
body = body + data //body 데이터에다가 callback 함수가 실행될 때마다 데이터를 추가해준다.
});
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);
'Back-End > App' 카테고리의 다른 글
[ NodeJS - APP ] 글 수정 정보 전송 (0) | 2021.08.12 |
---|---|
[ NodeJS - APP ] 글 수정 링크 생성 (0) | 2021.08.12 |
[ NodeJS - APP ] post 방식으로 전송된 데이터 받기 (0) | 2021.08.12 |
[ NodeJS ] 패키지 매니저와 PM2 (0) | 2021.08.11 |
[ NodeJS - APP ] 함수를 이용해서 정리 정돈하기 (0) | 2021.08.10 |