개발/Node.js

[nodeJS] 게시판 홀따옴표, 쌍따옴표 및 각종 특수문자 처리

개발자 솜 2021. 8. 2. 15:09

게시판 제목에서 '가 포함된 내용을 입력하면 db sql문에서 끝으로 인식하여 insert가 되지 않고 에러가 나는 상황이 발생했다.

그래서 db로 가기 전에 javascript에서 html 특수문자로 바꿔준 후 db에 넣고, 리스트를 가져올 때는 재변환하여 화면에 출력시켰다.

 

Reference : html 특수문자 리스트 : http://kor.pe.kr/util/4/charmap2.htm

 

HTML 특수문자 리스트

 

kor.pe.kr

writer.ejs

<script type="module" src="../../../public/js/writer.js"></script>

<input class="title-inputer" type="text" placeholder="제목">

 

writer.js


title = escapeHtml($('.title-inputer').val());

const entityMap = { 
    '&': '&amp;', 
    '<': '&lt;', 
    '>': '&gt;', 
    '"': '&quot;', 
    "'": '&#39;', 
    '/': '&#x2F;', 
    '`': '&#x60;', 
    '=': '&#x3D;' 
}; 

function escapeHtml(string) { 
    return String(string).replace(/[&<>"'`=\/]/g, function (s) { 
        return entityMap[s]; 

    }); 
}

 

board.js (nodejs) 

const entityMap = { 
  '&amp;': '&', 
  '&lt;': '<', 
  '&gt;': '>', 
  '&quot;': '"', 
  '&#39;': "'", 
  '&#x2F;': '/', 
  '&#x60;': '`', 
  '&#x3D;': '=' 
}; 

function unescapeHtml(string) { 
  return String(string).replace(/&amp;|&lt;|&gt;|&quot;|&#39;|&#x2F;|&#x60;|&#x3D;/g, function (s) { 
    return entityMap[s]; 
  }); 
  
}

router.get('/list/:page', async function(req, res, next){ 
  // DB에서 데이터 가져오기
  let postData = [];
  items = await service.pagingPosts(no, page_size);
  for(let item of items){
    let node = {
      'pkid':item['postPk'],
      'postTitle':unescapeHtml(item['postTitle']),
      'p_userPk':item['p_userPk'],
      'p_userName':item['p_userName'],
      'postContent':item['postContent'],
      'writeDate':item['writeDate'],
      'recentDate':item['recentDate'],
      'p_catePk':item['p_catePk'],
      'useable':item['useable'],
      'pCate':item['pCate'],
      'cCate':item['cCate']
    }
    postData.push(node)
  }
 
  });

 

Reference : https://epthffh.tistory.com/entry/javascript-jQuery%EB%A1%9C-HTML-%EB%AC%B8%EC%9E%90%EC%97%B4-%EC%9D%B4%EC%8A%A4%EC%BC%80%EC%9D%B4%ED%94%84-%EC%B2%98%EB%A6%AC%ED%95%98%EA%B8%B0