sanitize Html을 이용하여 express 미들웨어 만들기

Jaewoong2·2020년 7월 20일
0

boilerplate

목록 보기
4/13

html 태그등을 직접 서버로 넘기면, 잘못된 태그나 스크립트 태그들이 넘어 올 수 있습니다. 그 넘어 온 것을 또 화면단에 보여주면 이제 오류가 생길 수 있기 때문에 말그대로 '소독' 을 해줘야 합니다.

html 태그를 내가 원하는 속성 및 태그 들을 설정해서 받을 수 있습니다.

먼저 미들웨어를 만들어 봅시다

const sanitizeHtml = require('sanitize-html');
const sanitizeOption = {
    allowedTags : [
        'h1',
        'h2',
        'b',
        'i',
        'u',
        's',
        'p',
        'ul',
        'ol',
        'li',
        'blockquote',
        'a',
        'img',
    ],
    allowedAttributes : {
        a : ['href', 'name', 'target'],
        img : ['src'],
        li : ['class'],
    },
    allowedSchemes : ['data', 'http'],
};


exports.sanitizer = (req, res, next) => {
    const filtered = sanitizeHtml(req.body.content, {
        ...sanitizeOption
    });
    filtered.length < 200 ? filtered : `${filtered.slice(0, 200)}...`
    req.filtered = filtered;
    next();
}
  • 함수를 exports를 해줍니다.
  • (req, res, next) 를 받을 수 있습니다.
  • sanitizeHtml(설정해줄인자, 옵션) 의 형태로 넣어 줍니다.
  • return 값은 변환된 값입니다
  • 변환된 값을 받아
  • req.filtered 에 저장 해줍니다. (라우터에서 req.filtered을 접근 가능)

router.post('/', sanitizer ,async (req, res, next) => { 
        const post = await Post.create({
            title : req.body.title,
            content : req.filtered,
            UserId : req.user.id
        });
        

이렇게 Post를 만들 때, req.filtered를 content의 값에 넣어주면 된답니다 ~

profile
DFF (Development For Fun)

0개의 댓글