Home > database >  How Can I Send HTML string to Backend?
How Can I Send HTML string to Backend?

Time:12-15

I am using NextJs, I have a rich text editor my frontEnd. This output is html when i try to send this html with axios request to backend. I am getting error because format it is not json.

How can i send this html to backend service ? Is there any way ?

I download cheerio but ı don't understand.

CodePudding user response:

Please try to encode the HTML string using this function:

const escapeHTML = function(str){
  str.replace(/[&<>'"]/g, 
  tag => ({
      '&': '&amp;',
      '<': '&lt;',
      '>': '&gt;',
      "'": '&#39;',
      '"': '&quot;'
    }[tag]));
}

To decode the HTML string, you can use:

const decodeHTML = function(html) {
    let txt = document.createElement('textarea');
    txt.innerHTML = html;
    return txt.value;
};

Or:

const decodeHTML = function(input) {   
  let doc = new DOMParser().parseFromString(input, "text/html");   
  return doc.documentElement.textContent; 
}  

console.log(  decodeHTML("&lt;img src='img.jpg'&gt;")  )     
//Output: "<img src='img.jpg'>"
  • Related