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

React中使用axios获取base64格式README文件如何正常渲染内容?

解决方法

1. 解码Base64内容

Github Git Blobs API 返回的content字段是带换行符的Base64编码字符串,你需要先对内容做解码处理,浏览器环境可直接使用内置的atob方法,解码前要先删除内容中的所有换行符,避免解码失败。
如果文件包含非英文内容,还需要做编码兼容处理防止乱码,示例代码如下:

// 移除Base64字符串中的换行符
const rawBase64 = response.data.content.replace(/\n/g, '');
// 解码,兼容非英文内容
const decodedContent = decodeURIComponent(escape(atob(rawBase64)));

如果仅需要展示纯文本内容,把解码后的decodedContent直接渲染到普通标签即可,不需要额外依赖。

2. 渲染Markdown排版(可选)

如果要展示带格式的Markdown效果,需要安装Markdown渲染组件,推荐使用react-markdown:

  • 安装依赖
npm install react-markdown
# 或使用yarn
yarn add react-markdown

完整可运行代码

import "./styles.css";
import { useEffect, useState } from 'react';
import axios from 'axios';
import ReactMarkdown from 'react-markdown';

export default function App() {
  const [md, setMd] = useState('');
  useEffect(() => {
        async function fetchReadMeContents() {
            const response = await axios({
                url: "https://api.github.com/repos/zafar-saleem/anymnd/git/blobs/7af90ceab018a889b46634331cab822d94ff2b19",
            });
            const rawBase64 = response.data.content.replace(/\n/g, '');
            const decodedContent = decodeURIComponent(escape(atob(rawBase64)));
            setMd(decodedContent);
        }
        fetchReadMeContents();
    }, []);
  return (
    <div className="App">
      {/* 不需要Markdown格式的话直接把ReactMarkdown换成div即可 */}
      <ReactMarkdown>{md}</ReactMarkdown>
    </div>
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 12:09:03