게시판 애플리케이션에 에디터 기능을 강화하면 사용자가 풍부한 형식의 콘텐츠를 작성할 수 있어 사용자 경험이 향상됩니다. 이를 위해 WYSIWYG(What You See Is What You Get) 에디터를 통합하는 방법을 소개합니다.
1. WYSIWYG 에디터 선택 및 설치
대표적인 WYSIWYG 에디터인 TinyMCE를 사용하여 게시글 작성 기능을 향상시킬 수 있습니다. TinyMCE는 다양한 텍스트 포맷팅 옵션을 제공하며, 설치와 통합이 비교적 간단합니다.
2. TinyMCE 통합 단계
-
2.1. TinyMCE 스크립트 추가
views/new.ejs
파일의<head>
섹션에 TinyMCE 스크립트를 추가합니다.<script src="https://cdn.tiny.cloud/1/no-api-key/tinymce/6/tinymce.min.js" referrerpolicy="origin"></script> <script> tinymce.init({ selector: '#content', plugins: 'lists link image preview', toolbar: 'undo redo | formatselect | bold italic | alignleft aligncenter alignright | bullist numlist outdent indent | link image | preview', menubar: false, branding: false }); </script>
-
2.2. 게시글 작성 폼 수정
views/new.ejs
파일의 게시글 작성 폼에서textarea
요소에id="content"
를 추가하여 TinyMCE가 해당 요소를 에디터로 변환하도록 설정합니다.<form action="/create" method="post"> <label for="title">제목:</label> <input type="text" id="title" name="title" required> <br> <label for="content">내용:</label> <textarea id="content" name="content" required></textarea> <br> <button type="submit">작성</button> </form>
-
2.3. 게시글 표시 시 HTML 렌더링
views/index.ejs
파일에서 게시글 내용을 표시할 때 HTML 태그가 올바르게 렌더링되도록<%= post.content %>
를<%- post.content %>
로 수정합니다. 이렇게 하면 사용자 입력이 HTML로 해석되어 풍부한 형식이 적용됩니다.<% posts.forEach(post => { %> <li> <h2><%= post.title %></h2> <p><%- post.content %></p> <p><small><%= post.date %></small></p> </li> <% }) %>
3. 보안 고려사항
사용자 입력을 HTML로 렌더링할 때는 XSS(Cross-Site Scripting) 공격에 노출될 수 있으므로, 입력 내용을 저장하기 전에 서버 측에서 신뢰할 수 있는 HTML sanitizer를 사용하여 유해한 스크립트를 제거하는 것이 좋습니다. 예를 들어, sanitize-html
패키지를 사용할 수 있습니다.
npm install sanitize-html
그런 다음, 게시글 작성 처리 시 내용을 정화합니다.
const sanitizeHtml = require('sanitize-html');
// 게시글 작성 처리
app.post('/create', (req, res) => {
const { title, content } = req.body;
const sanitizedContent = sanitizeHtml(content, {
allowedTags: sanitizeHtml.defaults.allowedTags.concat([ 'img' ]),
allowedAttributes: {
'*': [ 'style', 'class' ],
'a': [ 'href', 'name', 'target' ],
'img': [ 'src' ]
}
});
const newPost = { title, content: sanitizedContent, date: new Date().toLocaleString() };
posts.push(newPost);
res.redirect('/');
});
이렇게 하면 사용자가 이미지, 링크 등을 포함한 다양한 형식의 게시글을 작성할 수 있으며, 보안도 강화할 수 있습니다.