반응형
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);
});
});
});
반응형
'Dev > Nodejs-express' 카테고리의 다른 글
[Nodejs-express] 미들웨어, body-parser, compression (0) | 2020.08.08 |
---|---|
[Nodejs-express] app.post(), res.redirect() (0) | 2020.08.07 |
[Nodejs-express] app.get() (0) | 2020.08.07 |
[Nodejs-express] 설치하기 (0) | 2020.08.07 |
[Nodejs-express] Nodejs 웹 프레임워크 Express? (0) | 2020.08.07 |