수정링크 생성 (홈페이지에서는 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 |