res.text() is not a function

Viewed 31

I have a simple html string like '<html><body><h1>hello world!!!!!</h1></body></html>'. I want to convert it to text but I am getting error like .text is not a function

My main purpose is to convert url into html. This is my code

      axios({
            method: 'get',
            url: url,
            headers:{
                "Content-Type":"text/html"
            },
        }).then(async (res) => {     
                const html = await res.data.text();
                console.log('html:', html);
        }).catch((e) => {
            console.log('e: ', e);
        })

I consoled res.data and I got html string but I am not able to convert it to text. i tried to put hardcoded html string to .text() but I am getting the same error that .text is not a function

2 Answers

If you're looking to get out of it only hello world!!!!!, then use DOMParser to turn it into a document, then get the document's text content.

axios(url)
  .then((res) => {     
    const htmlText = res.data;
    const doc = new DOMParser().parseFromString(htmlText, 'text/html');
    const plainTextContent = doc.body.textContent.trim();
    // use plainTextContent
  }).catch((e) => {
    console.log('e: ', e);
  });

If you specify the responseType in your request options, you can directly receive an HTML document without having to worry about parsing it

// just an example HTML page
const url = "https://jsonplaceholder.typicode.com/index.html";

axios.get(url, { responseType: "document" }).then(({ data }) => {
  // data is an HTML document
  const title = data.querySelector("h1").textContent;
  console.log("title:", title);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.27.2/axios.min.js" integrity="sha512-odNmoc1XJy5x1TMVMdC7EMs3IVdItLPlCeL5vSUPN2llYKMJ2eByTTAIiiuqLg+GdNr9hF6z81p27DArRFKT7A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

This is possible because Axios (when run in the browser) uses XMLHttpRequest which automatically supports rich (parsed) response types.

The Fetch API which is used in the post you linked to unfortunately does not support such a convenience and the response must be parsed.

Related