오도원입니다.

건강과 행복을 위하여

프로젝트/니랑내랑

Express 4. 생성, 수정, 삭제

오도원공육사 2020. 2. 19. 14:20
반응형
const express = require('express');
const app = express();
const fs = require('fs');
const template = require('./lib/template.js');
const path = require('path');
const sanitizeHtml = require('sanitize-html');
const qs = require('querystring');

app.get('/', (req, res) => {
    fs.readdir('./data', (err, filelist) => {
        var title = 'Welcome home!';
        var description = 'Hello, Node.js';
        var list = template.list(filelist);
        var html = template.HTML(title, list,
          `<h2>${title}</h2>${description}`,
          `<a href="/create">create</a>`
        );
        res.send(html); 
      });
});

app.get('/page/:pageId', (req, res) => {
    fs.readdir('./data', (err, filelist) => {
        var filteredId = path.parse(req.params.pageId).base;
        console.log('pageId : ', filteredId);
        fs.readFile(`data/${filteredId}`, 'utf8', (err, description) => {
            var title = req.params.pageId;
            var sanitizedTitle = sanitizeHtml(title);
            var sanitizedDescription = sanitizeHtml(description, {
                allowedTags:['h1']
            });
            var list = template.list(filelist);
            var html = template.HTML(sanitizedTitle, list,
                `<h2>${sanitizedTitle}</h2>${sanitizedDescription}`,
                ` <a href="/create">create</a>
                <a href="/update/${sanitizedTitle}">update</a>
                <form action="/delete_process" method="post">
                    <input type="hidden" name="id" value="${sanitizedTitle}">
                    <input type="submit" value="delete">
                </form>`
            );
            res.send(html);
        });
    });
});

app.get('/create', (req, res) => {
    fs.readdir('./data', (err, filelist) => {
        var title = 'WEB - create';
        var list = template.list(filelist);
        var html = template.HTML(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>
        `, '');
        res.send(html);
    });
});

app.post('/create_process', (req, res) => {
    var body = '';
    req.on('data', (data) => {
        body = body + data;
    });
    req.on('end', () => {
        var post = qs.parse(body);
        var title = post.title;
        var description = post.description;
        fs.writeFile(`data/${title}`, description, 'utf8', (err) => {
          res.redirect(`/page/${title}`);
        });
        console.log('create', title);
    });
    
});

app.get('/update/:pageId', (req, res) => {
    fs.readdir('./data', (err, filelist) => {
        var filteredId = path.parse(req.params.pageId).base;
        console.log(req.params.pageId);
        fs.readFile(`data/${filteredId}`, 'utf8', (err, description) => {
          var title = req.params.pageId;
          var list = template.list(filelist);
          var html = template.HTML(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/${title}">update</a>`
          );
          res.send(html);
        });
    });
});

app.post('/update_process', (req, res) => {
    var body = '';
        req.on('data', (data) => {
          body = body + data;
        });
        req.on('end', () => {
            var post = qs.parse(body);
            var id = post.id;
            var title = post.title;
            var description = post.description;
            fs.rename(`data/${id}`, `data/${title}`, (err) => {
                fs.writeFile(`data/${title}`, description, 'utf8', (err) => {
                res.redirect(`/page/${title}`);
            });
        });
    });
});

app.post('/delete_process', (req, res) => {
    var body = '';
    req.on('data', (data) => {
        body = body + data;
    });
    req.on('end', () => {
        var post = qs.parse(body);
        var id = post.id;
        var filteredId = path.parse(id).base;
        fs.unlink(`data/${filteredId}`, (err) => {
            res.redirect(`/`);
        });
    });
})

app.listen(3000, () => console.log('Example app listening on port 3000!'));

 

톺아보기

1. querystring 모듈

cosnt qs = require('querystring');

 

2. 생성

app.get('/create', (req, res) => {
	fs.readdir('./data', (err, filelist) => {
		var title = 'WEB - create';
        var list = template.list(filelist);
        var html = template.HTML(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>
            `, '');
        res.send(html);
    });
});

app.post('/create_process', (req, res) => {
	var body = '';
    req.on('data', (data) => {
    	body = body + data;
    });
    req.on('end', () => {
		var post = qs.parse(body);
        var title = post.title;
        var description = post.description;
        fs.writeFile(`data/${title}`, description, 'utf8', (err) => {
        	res.redirect(`/page/${title}`);
        });
    });
});

 

반응형

'프로젝트 > 니랑내랑' 카테고리의 다른 글

미들웨어란 무엇인가  (0) 2020.02.19
Express 5. 미들웨어 사용하기 body-parser  (0) 2020.02.19
pm2 패키지  (0) 2020.02.19
Express 3. 상세보기 페이지 구현  (0) 2020.02.19
Express 2. 홈페이지 구현  (0) 2020.02.19