1 minute read

22. sanitize-html 사용하기

Install module from console:
npm install sanitize-html

Use it in your node app:

var sanitizeHtml = require('sanitize-html');

var dirty = 'some really tacky HTML';
var clean = sanitizeHtml(dirty);

html 태그들로 오염된 문장을 clean 시켜준다.

  • main.js 추가

    var sanitizeHtml = require('sanitize-html');
    

require하면 nodejs 는 node-modules 에서 santize-html을 찾는다.
그 모듈에 sanitizeHtml 이라는 변수명을 붙인다.

  • 상세보기 페이지
    title과 description을 sanitize 한다.

    var sanitizedTitle = sanitizeHtml(title);
    var sanitizedDescription = sanitizeHtml(description);
    

별도의 변수를 사용한다. 이렇게 하는게 좋은 이유는 자신이 사용하는 변수가 살균이 되었는지
변수 이름을 통해 알 수 있다.

/create 에서 파일을 새로 생성한다.

title : dirty HTML
description :
This is dirty.
<script/alert('hi')/script>
end.

페이시 소스 보기와 생성된 파일을 보면,
script 태그 부분이 사라진(소독, 살균)된 것을 확인 할 수 있다.

/h1>This is dirty</h2 추가

<h1/같은 /script/보다 덜 예민한 태그도 똑같이 없어지지만 내용은 살려준다.
<h1/태그를 살리고 싶다면 태그를 허용해야한다.

---
// Allow only a super restricted set of tags and attributes
clean = sanitizeHtml(dirty, {
  allowedTags: [ 'b', 'i', 'em', 'strong', 'a' ],
  allowedAttributes: {
    'a': [ 'href' ]
  },
  allowedIframeHostnames: ['www.youtube.com']
});
---

santizeHtml 함수를 호출할 때 두 번째 인자로 객체를 준다.

var sanitizedDescription = sanitizeHtml(description, {
              allowdTags:['h1']
});

h1 태그가 허용된다.
들어오는 정보, 나가는 정보를 문제 없이 처리한다.


처음에, node 서버가 실행이 안되서 pm2 log로 확인해보니 ‘MODULE_NOT_FOUND’

잘못된 npm 모듈 설치했기 때문. npm install -S sanitize

nodejs 에서 npm 모듈 제거하기

npm uninstall sanitize

npm install -S sanitize-html 로 재설치