記事生成UIの作成
77154 ワード
復習する
input tagやtextarea tagのように入力された情報があれば、tag全体をform tagで包みます.
フォームタグのactionプロパティは、フォームデータをサーバに送信するときに、そのデータが到着したURLを受信します.
<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>
HTTPとは?
ハイパーテキスト転送プロトコル(HTTP)は、HTMLなどのハイパーメディアドキュメントを転送するためのアプリケーション層プロトコルである.HTTPは従来のクライアント-サーバモードに従い、クライアントは接続を開いて要求を作成し、応答を待つ.
HTTP通信時に送信されるデータをHTTPパケットと呼び,その構成は大きく分けてHeader領域とBody領域に分けられる.また、どの方法を使用するかは、Body領域の可用性と使用方法に影響します.
GetとPost
Get、Postメソッドは、HTTPプロトコルがデータ転送をサポートする7つのメソッドの一部である.
通常、CRUDにCUDが含まれている場合はPostメソッドを使用し、データのみを選択する場合はGetメソッドを使用します.
<Getメソッド>
*Body領域
Ex.1回の要求で最大255文字(256バイト)の
◇Bodyゾーン
◇複雑な形式のデータ伝送に非常に有用である
Get方式でURLデータを受信
//요청이 http://localhost:3000/?id=inha 일경우
var url = require('url');
var http = require('http');
var app = http.createServer(function(request,response){
var _url = request.url; // /?id=ohayo
var queryData = url.parse(_url,true).query; // [Object: null prototype] {id: 'ohayo'}
var title = queryData.id; // inha
});
app.listen(3000, function(){console.log('connected!')});
POST方式でFORMデータを受信する
var qs = require('querystring');
var http = require('http');
var app = http.createServer(function(request,response){
var body = '';
request.on('data',function (data){ //request의 데이터를 data로
body += data;
if (body.length > ie6){ //ie 6 은 숫자
request.connection.destroy(); // 접속끊는 함수
}
});
request.on('end',function(){ // data가 끝낫을경우 실행
var post= qs.parse(body); // body 를 쿼리스트링으로 형식바꿈
console.log(post); // queryString 출력
})
response.writeHead(302, {Location: `/?id=${}`}); //요청한 주소로 리다이렉션
response.end('sucess');
});
Post方式でデータを取得するには、約束されたイベントが必要です.request.on(「data」,function(data){}は
リクエスト方式で入力したデータをスライス
コールバック関数の dataで入れるという意味
ブロック入れなので全部受け取るためにbody+=dataを入れます
request.connection.destroy(); 表示
接続を解除する関数.if文の使用
データが一定サイズを超える場合は、切断された関数を使用します.
request.on(「end」,function(){}は
リクエストデータを受信して作業します.qs.parse()メソッドの使用
requestからbodyを受信したすべてのデータをquerystringフォーマットに変換します.
再補正とは何ですか。
ユーザーが入力したデータを送信し、データが正しいことを確認します.
ユーザーを別のページに移動することをリダイレクトと呼びます.
転送302は、
writeHead(302,{Location: })
フォーマットを使用して、上記のコンテンツをタイトルに送信する.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.writeHead(302, {Location: `/?id=${qs.escape(title)}`});
response.end();
});
});
ファイルの入力時に作成、リストの変更、およびアドレスの変更を行う手順は、次のとおりです.->該当するアドレスの完了->ページ
更新機能の実装
更新機能を実現するために、
1)変更するファイルの既存値の取得(fs.readdir、fs.readFile)
2)form形式で既存のコンテンツを表示する(inputトピックのvalueプロパティ)
3)コミットされたデータの受信(request.on)
4)ファイル名と内容の変更(fs.rename,fs.writeFile)
5)idページにリダイレクト(response.writeHead(302,{位置:})
必要です.
既存の情報を視線に隠す
formを使用してデータを転送する場合(Post)は、既存の情報を同時に送信する必要があります.
変更するファイルが表示されます.
ただし、既存の情報をユーザーに表示する必要はありません.
type=「hidden」プロパティを使用すると、フォームデータを非表示の場所に送信できます.
ただし、hidden formでは情報を入力できません.
valueラベルを使用してデフォルト値を入力します.
<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>
伝達された情報の受信と変更
request.onroformデータを受信しfsを入力します.ファイル名をfsと名付けます.writeFileを使用してファイルの内容を変更します.
fs.writeFileは、内部の作成と変更に使用できます.
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;
console.log(post.id); // inha
console.log(post.title); // INHA UNIV
console.log(post.description); // hi inha~
fs.rename(`data/${id}`,`data/${title}`, function(error){ // 파일 이름 변경
// 첫번째 인자에 기존 이름, 두번째 인자에 변경하려는 이름
fs.writeFile(`data/${title}`,description, 'utf8', function(err){ // 파일 내용 변경
// writeFile은 파일 내용 생성, 수정 모두에 쓰임
response.writeHead(302, {Location: `/?id=${qs.escape(title)}`});
response.end();
});
});
});
記事削除ボタンの実装
削除などの重要な機能は、他人が勝手に情報を削除しないように郵送する必要があります.
そこで、削除ボタンをpost形式でラップします.
hidden formを使用してファイル名を非表示にします.
ボタンの名前をvalueプロパティに変更できます.
<form action="delete_process" method = "post">
<input type="hidden" name="id" value="${title}">
<input type="submit" value="delete">
// submit에서는 value가 버튼 이름
</form>
記事削除機能の実装
フォームから値(ファイル名)を取得するように要求します.onを使用します.
受信したファイル名はfsです.unlink関数に渡して、名前のあるファイルを削除します.
else if(pathname === '/delete_process'){
var body ='';
request.on('data',function(data){
body = body + data;
});
// form data를 받기 위해 request.on('data',function(data){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();
})
});
}
すべてをまとめる
href=「or action=」移動先アドレスを指定します.
if文でpathnameまたはqyerydataを指定する場合.idで調査(Get)し、対応するページを整理します.
form tagのactionにデータを送信
このアドレスは、フォームに送信されたデータを受信します.
リダイレクトを使用して別のページに移動するタスクを実行します.
◇データアドレスを受信したページは、ユーザーには見えません.
// 모듈 require
var http = require('http');
var fs = require('fs');
var url = require('url');
var qs = require('querystring');
// template literal을 html로 return 하는 함수
function templateHTML(title, list, body, control){
return `
<!doctype html>
<html>
<head>
<title>WEB - ${title}</title>
<meta charset="utf-8">
</head>
<body>
<h1><a href="/">WEB</a></h1>
${list}
${control}
${body}
</body>
</html>
`;
}
// 전달받은 배열을 리스트로 return 하는 함수
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;
}
// nodeis의 서버 생성 방법 : http객체의 createServer, listen
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 === '/'){ // pathname /
if(queryData.id === undefined){ // id 존재 x (Home)
fs.readdir('./data', function(error, filelist){
var title = 'Welcome';
var description = 'Welcome to 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 { // id 존재 o
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>`);// form을 쓴다고 다 post방식이 아님 폼데이터로 받으려면 method 속성이 반듯있음
response.writeHead(200);
response.end(template);
});
});
}}
else if(pathname == '/create') { // 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>
`,'');
// <form> 태그의 action 속성은 폼 데이터(form data)를 서버로 보낼 때 해당 데이터가 도착할 URL
response.writeHead(200);
response.end(template);
})}
else if (pathname === '/create_process'){ // 데이터가 전송되는 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=${qs.escape(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; // form hidden으로 추가된 id값도 받을 수 있게!
var title = post.title;
var description = post.description;
console.log(post.id); // inha
console.log(post.title); // INHA UNIV
console.log(post.description); // inha
fs.rename(`data/${id}`,`data/${title}`, function(error){ // 파일이름 변경하는 fs.rename 함수 사용
fs.writeFile(`data/${title}`,description, 'utf8', function(err){ // writeFile은 수정하는 기능도 있나봄!
response.writeHead(302, {Location: `/?id=${qs.escape(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, function(){
console.log('연결되었습니다!');
});
👉Reference
この問題について(記事生成UIの作成), 我々は、より多くの情報をここで見つけました https://velog.io/@nayonsoso/생활코딩-실습-글생성-UI-만들기テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol