axios获取HTML后调用.text()报错,如何将HTML转纯文本?
问题解答
1. .text()方法存在吗?
存在,但不是JavaScript字符串的方法。它是浏览器Fetch API中Response对象的方法,用于将响应流转换为文本格式。但你使用的axios已经自动将响应内容解析成字符串返回,因此不需要调用这个方法。
2. 报错原因
res.data本身就是解析后的HTML字符串,而JavaScript的字符串类型并没有text()方法,直接调用自然会抛出.text is not a function的错误。
3. 解决方案
方案一:直接获取HTML内容
如果你的核心需求是获取URL返回的HTML内容,直接使用res.data即可,无需额外处理:
axios({ method: 'get', url: url, headers:{ "Content-Type":"text/html" }, }).then((res) => { const html = res.data; console.log('html:', html); }).catch((e) => { console.log('e: ', e); })
方案二:将HTML字符串转为纯文本
如果实际需求是提取HTML中的纯文本内容,可采用以下两种方式:
方式1:利用DOM API(仅浏览器环境)
通过创建临时DOM元素解析HTML,提取文本内容,这种方式兼容性好且处理复杂HTML更可靠:
function htmlToPlainText(htmlStr) { const tempDiv = document.createElement('div'); tempDiv.innerHTML = htmlStr; return tempDiv.textContent || tempDiv.innerText; } // 调用示例 axios({ method: 'get', url: url, headers:{ "Content-Type":"text/html" }, }).then((res) => { const plainText = htmlToPlainText(res.data); console.log('纯文本内容:', plainText); }).catch((e) => { console.log('e: ', e); })
方式2:正则表达式替换(浏览器/Node.js通用)
适合结构简单的HTML,通过正则去掉所有标签:
function htmlToPlainText(htmlStr) { return htmlStr.replace(/<[^>]+>/g, '').replace(/\s+/g, ' ').trim(); } // 调用示例 axios({ method: 'get', url: url, headers:{ "Content-Type":"text/html" }, }).then((res) => { const plainText = htmlToPlainText(res.data); console.log('纯文本内容:', plainText); }).catch((e) => { console.log('e: ', e); })
内容的提问来源于stack exchange,提问作者Srushti Shah
相关产品推荐
相关产品推荐

