You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用React实现点击按钮在浏览器渲染服务器返回的HTML文件?

解决React中fetch获取HTML文件报错及展示问题

报错原因及修复

你遇到的SyntaxError是因为调用了fetch的.json()方法,但服务器返回的是HTML文本而非JSON格式,解析自然失败。只需把解析方式换成.text()即可获取正确的HTML内容:

fetch('/你的接口地址', {
  method: 'POST',
  body: JSON.stringify({ filename: '目标文件名' }),
  headers: {
    'Content-Type': 'application/json'
  }
})
.then(response => {
  if (!response.ok) throw new Error('请求失败');
  return response.text(); // 用text()替代json()获取HTML内容
})
.then(htmlContent => {
  // 后续处理HTML展示逻辑
})
.catch(error => console.error('请求出错:', error));

浏览器展示HTML的三种方法

方法1:在组件内直接渲染(使用dangerouslySetInnerHTML)

适合需要嵌入当前页面的场景,注意确保HTML内容安全,避免XSS风险:

import { useState } from 'react';

function HtmlFileViewer() {
  const [htmlContent, setHtmlContent] = useState('');

  const loadHtmlFile = () => {
    fetch('/你的接口地址', {
      method: 'POST',
      body: JSON.stringify({ filename: 'test.html' }),
      headers: {
        'Content-Type': 'application/json'
      }
    })
    .then(res => res.text())
    .then(html => setHtmlContent(html))
    .catch(err => console.error(err));
  };

  return (
    <div>
      <button onClick={loadHtmlFile}>加载HTML文件</button>
      <div dangerouslySetInnerHTML={{ __html: htmlContent }} />
    </div>
  );
}

export default HtmlFileViewer;

方法2:使用iframe展示

适合需要隔离HTML环境的场景,通过Blob创建临时URL:

import { useState } from 'react';

function HtmlFileViewer() {
  const [iframeUrl, setIframeUrl] = useState('');

  const loadHtmlFile = () => {
    fetch('/你的接口地址', {
      method: 'POST',
      body: JSON.stringify({ filename: 'test.html' }),
      headers: {
        'Content-Type': 'application/json'
      }
    })
    .then(res => res.blob())
    .then(blob => {
      const tempUrl = URL.createObjectURL(blob);
      setIframeUrl(tempUrl);
      // 组件卸载时释放临时URL,避免内存泄漏
      return () => URL.revokeObjectURL(tempUrl);
    })
    .catch(err => console.error(err));
  };

  return (
    <div>
      <button onClick={loadHtmlFile}>加载HTML文件</button>
      {iframeUrl && <iframe src={iframeUrl} width="100%" height="600px" />}
    </div>
  );
}

export default HtmlFileViewer;

方法3:新开窗口展示

适合需要独立页面查看的场景:

const loadHtmlInNewWindow = () => {
  fetch('/你的接口地址', {
    method: 'POST',
    body: JSON.stringify({ filename: 'test.html' }),
    headers: {
      'Content-Type': 'application/json'
    }
  })
  .then(res => res.text())
  .then(html => {
    const newWindow = window.open();
    newWindow.document.write(html);
    newWindow.document.close();
  })
  .catch(err => console.error(err));
};

内容的提问来源于stack exchange,提问作者SHERAWAT LOKESH

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 21:21:12