<a href="/update">update</a>
라고 써주면 되는건 맞는데, 메인 페이지나 글을 쓰는(create)페이지에서는 update가 필요 없으므로 templateHTML 함수를 수정해서 create/update 링크를 파라미터로 넘길 수 있게 해준다.
function templateHTML(title, list, body, control){
return `
<!doctype html>
<html>
<head>..</head>
<body>
<h1><a href="/">WEB</a></h1>
${list}
${control}
${body}
</body>
</html>
`;
}
if(pathname === '/'){
//메인페이지
if(queryData.id === undefined){
fs.readdir('./data', function(error, filelist){
...
var template = templateHTML(title, list, `<h2>${title}</h2>${description}`,
`<a href="/create">create</a>`);
...
})
} else {
//각 data 페이지
fs.readdir('./data', function(error, filelist){
fs.readFile(`data/${queryData.id}`, 'utf8', function(err, description){
...
var template = templateHTML(title, list, `<h2>${title}</h2>${description}`,
`<a href="/create">create</a> <a href="/update?id=${title}">update</a>`);
...
});
});
}
}
pathname이 update일 경우
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="/process_update" 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" value="${description}"></textarea></p>
<p><input type="submit"></p>
`,
`<a href="/create">create</a> <a href="/update?id=${title}">update</a>`);
response.writeHead(200);
response.end(template);
});
});
}
<input type="
hidden
" name"id" value="${title}">
사용자에게는 보이지 않는, 숨겨진 입력필드
폼 제출 시 사용자가 변경해서는 안 되는 데이터를 함께 보낼 때 유용하게 사용된다.
else if(pathname === '/process_update'){
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}`, (error)=>{
fs.writeFile(`data/${title}`, description, 'utf8', function(err){
response.writeHead(302, {Location: `/?id=${title}`});
response.end();
})
});
});
}