본문 바로가기
Dev/Nodejs-express

[Nodejs-express] req.params

by Ellen571 2020. 8. 7.
반응형

[생활코딩] 상세보기 페이지 구현

 

 

Route parameters

- Route path: /users/:userId/books/:bookId   --- route path를 지정

- Request URL: http://localhost:3000/users/34/books/8989   --- 사용자가 해당 url로 접속하면

- req.params: { "userId": "34", "bookId": "8989" }  --- req.params의 객체에 해당 형식으로 값이 들어옴

 

app.get('/page/:pageId/:chapterId', function(req, res){
  res.send(req.params);
});

 

localhost:3000/page/aaa/bbb로 접속

[결과]

{"pageId":"aaa","chapterId":"bbb"}

 

 

main.js

const express = require('express');
const app = express();
var fs = require('fs');
var template = require('./lib/template');
var path = require('path');
var sanitizeHtml = require('sanitize-html');

app.get('/page/:pageId', function(req, res){
  fs.readdir('./data', function(error, filelist){
    var filteredId = path.parse(req.params.pageId).base;
    // req.params로 pageId값 가져오고
    // path.parse로 pageId값 분석하여 base(파일명.확장자)부분만 가져오기
    
    fs.readFile(`data/${filteredId}`, 'utf8', function(err, description){
      var title = req.params.pageId; // title값 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?id=${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);
    });
  });
});
반응형