Search code examples
javascripthtmlnode.jsmongooseejs

How do I export mongodb html code to html file?


How do I display an html data piece from mongo db correctly?

Data: The html was encoded

What it shows: Not showing correctly

Code:

<script defer>
      function decodeHtml(html) {
    var txt = document.createElement("textarea");
    txt.innerHTML = html;
    return txt.value;
}
      
    const description = document.getElementById("descontainer")

    description.innerHTML += decodeHtml('<%= post.post.description %>')
 </script>


Solution

  • Not really sure why you put that html on a textarea element. But if the content is comming from a database that is contain use generated content, then you probele need an html sanitizer like dompurify.

    You will use it like this:

    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dompurify/2.3.6/purify.min.js" integrity="sha512-DJjvM/U3zCRpzrYboJgg23iLHapWcS2rlo7Ni18Cdv+FMs6b3gUF7hQihztj4uVkHHfUwk7dha97jVzRqUJ7hg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    
    <script defer>
       function decodeHtml(html) {
                
          return DOMPurify.sanitize(html);;
       }
              
       const description = document.getElementById("descontainer")
    
       description.innerHTML += decodeHtml('<%= post.post.description %>')
    </script>