| 일 | 월 | 화 | 수 | 목 | 금 | 토 | 
|---|---|---|---|---|---|---|
| 1 | ||||||
| 2 | 3 | 4 | 5 | 6 | 7 | 8 | 
| 9 | 10 | 11 | 12 | 13 | 14 | 15 | 
| 16 | 17 | 18 | 19 | 20 | 21 | 22 | 
| 23 | 24 | 25 | 26 | 27 | 28 | 29 | 
| 30 | 
                            Tags
                            
                        
                          
                          - 분류
 - LLM
 - 머신러닝
 - gpt
 - Classification
 - supervised learning
 - 해커톤
 - 회귀
 - LG Aimers 4th
 - ChatGPT
 - PCA
 - LG Aimers
 - GPT-4
 - LG
 - OpenAI
 - deep learning
 - AI
 - 지도학습
 - 티스토리챌린지
 - regression
 - 오블완
 - Machine Learning
 - 딥러닝
 
                            Archives
                            
                        
                          
                          - Today
 
- Total
 
SYDev
[Node.js] 12. 글생성 UI 만들기 본문
해당 게시물은 유튜브 생활코딩 "Node.js" 강의 영상을 참고했습니다.
(https://www.youtube.com/watch?v=3RS_A87IAPA&list=PLuHgQVnccGMA9QQX5wqj6ThK7t2tsGxjm&index=1)
HTML form
main.js와 같은 디렉토리에 다음 내용이 포함된 form.html 파일 생성
//method = "get" 혹은 디폴트 상황에서는 url에 데이터를 포함한다.
//서버 데이터를 수정, 삭제, 생성할 때는 url에서 데이터를 가려주는 method = "post"를 이용하자.
<form action = "http://localhost:3000/process create" method = "post">
    <p><input type = "text" name = "title"></p>
    <p>
        <textarea name = "description"></textarea>
    </p>
    <p>
        <input type = "submit">
    </p>
</form>
form.html 파일을 실행했을 때, 다음과 같이 데이터를 입력하는 페이지가 나옴

title, description을 모두 입력하고 제출하면 해당 데이터를 포함한 쿼리를 가진 url로 이동
>> http://localhost:3000/process%20create
method = "get" 이용할 시에는
>> http://localhost:3000/process%20create?title=hi&description=lorem
(title에 "hi", description에 "lorem" 입력)
글생성 UI 만들기
var http = require('http');
var fs = require('fs');
var url = require('url');
function templateHTML(title, list, body) {
  return `
  <!doctype html>
  <html>
  <head>
    <title>WEB - ${title}</title>
    <meta charset="utf-8">
  </head>
  <body>
    <h1><a href="/">WEB2</a></h1>  
    ${list}
    <a href = "/create">create</a>
    ${body}
  </body>
  </html>
  `;
}
function templateList(filelist) {
  var list = '<ol>';
  var i = 0;
  while(i < filelist.length) {
    list += `<li><a href="/?id=${filelist[i]}">${filelist[i]}</a></li>`;
    i++;
  }
  list += '</ol>';
  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);
        //place holder는 text input 박스 안에 나타나는 텍스트
        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);
      }); 
    }
    else {
      response.writeHead(404);
      response.end('Not found')
    }
});
app.listen(3000);
>> pathname이 /create인 url로 이동하는 버튼을 만들고, pathname이 /create인 경우에 데이터를 입력받는 텍스트 박스를 추가

>> title에 "Nodejs", description에 "Node.js is..." 입력할 시에 다음과 같은 화면

>> 우클릭 후 검사를 누르면 다음과 같이 웹 브라우저와 웹 서버가 주고받는 데이터를 볼 수 있는데, Form Data에 title과 description이 은밀하게 전달된 것을 확인할 수 있다.
728x90
    
    
  반응형
    
    
    
  '대딩코딩 > 웹개발 스터디' 카테고리의 다른 글
| [Node.js] 14. 파일 생성과 리다이렉션 (0) | 2023.11.18 | 
|---|---|
| [Node.js] 13. Post 방식으로 전송된 데이터 받기 (0) | 2023.11.18 | 
| [Node.js] 11. 패키지 매니저와 PM2 (1) | 2023.11.18 | 
| [Node.js] 10. 동기와 비동기 & callback (0) | 2023.11.18 | 
| [Node.js] 9. 함수 (1) | 2023.11.18 |