본문 바로가기

Back-End/Node.js

Express - 14.1. 라우터 - 주소체계변경

반응형

목표

현업에서는 라우트 개수가 1000개 2000개로 엄청 많다. 이를 정리하는 테크닉을 배우자.

(1) 주소체계 변경 <-

(2) 파일로 분리

 


주소체계 변경

- /page -> /topic

- /delete_process -> /topic/delete_process

- /create -> /topic/create

- 위의 세 경우 코드를 pageid 위로 옮김

const express = require('express');
const app = express();
const fs = require('fs');
const path = require('path');
const qs = require('querystring');
const sanitizeHtml = require('sanitize-html');
const template = require('./lib/template');
const bodyParser = require('body-parser');
const port = 3000;
const compression = require('compression');

app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(compression());
app.get('*', function(request, response, next) {
  fs.readdir('./data', function(err, filelist){
    request.list = filelist;
    next();
  });
});

// 1. 홈 페이지
// app.get('/', (req, res) => {  res.send('Hello World!')})
app.get('/', function(request, response){
  var title = 'Welcome';
  var description = 'Hello, Node.js';
  var list = template.list(request.list);
  var html = template.html(title, list,
    `<a href="/topic/create">create</a>`,
    `<h2>${title}</h2>${description}
    <img src="/images/hello.jpg" style="width:300px"; display:block; margin-top: 10px;>`
  );
  response.send(html);
});

//3. Create 버튼 클릭 시 페이지
app.get('/topic/create', function(request, response){
  var title = 'WEB - create';
  var list = template.list(request.list);
  var html = template.html(title, list,
    '',
    `
    <form action="/topic/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.send(html);
});

//4. create>제출 버튼 클릭 시 페이지
app.post('/topic/create', function(request, response){
  var post = request.body;
  var title = post.title;
  var description = post.description;
  fs.writeFile(`data/${title}`, description, 'utf8',
  function(err) {
    response.redirect(`/topic/${title}`);
  });
});

//5. update 버튼 클릭 시 페이지
app.get('/topic/update/:pageId', function(request, response){
  var filteredId = path.parse(request.params.pageId).base;
  fs.readFile(`data/${filteredId}`, 'utf8', function(err, description){
    var title = request.params.pageId;
    var list = template.list(request.list);
    var html = template.html(title, list,
      //form 부분
      `
      <form action="/topic/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">${description}</textarea>
        </p>
        <p><input type="submit"></p>
      </form>
      `,
      ``);
    response.send(html);
  });
});

//6. update>제출 버튼 클릭 시 페이지
app.post('/topic/update', function(request, response){
  console.log(request.list);
  var post=  request.body;
  var id = post.id;
  var title = post.title;
  var description = post.description;
  fs.rename(`data/${id}`, `data/${title}`, function(err){
    fs.writeFile(`data/${title}`, description, 'utf8',
    function(err) {
      response.redirect(`/topic/${title}`);
    });
  });
})

//7. delete 버튼 클릭 시 페이지
app.post('/topic/delete_process', function(request, response){
 var post = request.body;
  var id = post.id;
  var filteredId = path.parse(id).base;
  fs.unlink(`data/${filteredId}`, function(error){
    response.redirect('/');
  });
})

// 2. pageId 링크 클릭 시 페이지
app.get('/topic/:pageId', function(request, response, next){
  var filteredId = path.parse(request.params.pageId).base;
  fs.readFile(`data/${filteredId}`, 'utf8', function(err, description){
    if(err){
      next(err);
    }else{
      var title = request.params.pageId;
      var sanitizedTitle = sanitizeHtml(title);
      var sanitizedDescription = sanitizeHtml(description);
      var list = template.list(request.list);
      var html = template.html(sanitizedTitle, list,
        `<a href="/topic/create">create</a>
        <a href="/topic/update/${sanitizedTitle}">update</a>
        <form action="/topic/delete_process" method="post">
          <input type="hidden" name="id" value="${sanitizedTitle}">
          <input type="submit" value="delete">
        </form>
        `,
        `<h2>${sanitizedTitle}</h2>${sanitizedDescription}`);
      response.send(html);
    }
  });
});

app.use(function(req, res, next){
  res.status(404).send('sorry cant find that!');
});

app.use(function(err, req, res, next){
  console.error(err.stack);
  res.status(500).send('something broke!');
});

app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`))
반응형