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

Next.js(TS)应用调用GitHub API遇CORS及401错误求助

问题:Next.js(TS)前端调用GitHub API获取公开仓库内容返回401错误

我正在开发Next.js React(TS)应用,需要调用GitHub API获取公开仓库的文件内容。已经在next.config.mjs中配置了CORS规则:

const nextConfig = {
    async headers() {
        return [
            {
                source: "/:path*",
                headers: [
                    { key: "Access-Control-Allow-Credentials", value: "true" },
                    { key: "Access-Control-Allow-Origin", value: "*" },
                    { key: "Access-Control-Allow-Methods", value: "GET,DELETE,PATCH,POST,PUT" },
                    { key: "Access-Control-Allow-Headers", value: "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" },
                ]
            }
        ]
    }
}

前端请求代码如下:

useEffect(() => {
    const fetchCode = async () => {
        const response = await fetch(`https://api.github.com/repos/Kanav-Arora/DSA-Guide/contents/Binary Search/binary_search.cpp`, {
            headers: {
                Authorization: `Bearer ${github_api}`,
            },
            method: 'get',
            mode: 'cors',
        });
        console.log(response);
    }
    fetchCode();
}, [cpp])

但返回响应为:

Response {type: 'cors', url: 'https://api.github.com/repos/Kanav-Arora/DSA-Guide/contents/Binary%20Search/binary_search.cpp', redirected: false, status: 401, ok: false, …}

该请求在Postman中可正常运行,但开发环境下失败,想知道是否需要通过服务器发起GitHub API请求,以及具体解决办法。


解答

不需要额外搭建独立服务器,用Next.js自带的API路由做代理就能解决问题,核心是你当前的配置和做法存在两个关键问题:

1. Next.js的CORS配置方向错误

你在next.config.mjs里配置的CORS规则,是给你的Next.js应用自身接口设置跨域允许,和GitHub API的跨域无关。GitHub API本身已经支持CORS,但前端直接携带Token请求会触发浏览器的安全限制,同时暴露Token存在风险。

2. 前端直接暴露GitHub Token的安全隐患

把GitHub Token写在前端代码里,用户可以轻易通过浏览器控制台获取,可能导致Token被滥用,这是必须避免的。

具体解决步骤:用Next.js API路由做代理

步骤1:创建API代理文件

在pages/api目录下新建github-proxy.ts(或.js),代码如下:

import type { NextApiRequest, NextApiResponse } from 'next'

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const { repoPath } = req.query;
  if (!repoPath) {
    return res.status(400).json({ error: 'repoPath 参数缺失' });
  }

  try {
    const githubResponse = await fetch(`https://api.github.com/repos/${repoPath}`, {
      headers: {
        Authorization: `Bearer ${process.env.GITHUB_API_TOKEN}`,
        // 如果需要获取原始文件内容,添加这个请求头
        Accept: 'application/vnd.github.v3.raw',
      },
    });

    // 根据返回内容类型选择处理方式:文件内容用text(),JSON数据用json()
    const data = await githubResponse.text();
    res.status(githubResponse.status).send(data);
  } catch (error) {
    res.status(500).json({ error: '请求GitHub API失败' });
  }
}

步骤2:配置环境变量

在项目根目录的.env.local文件中添加你的GitHub Token:

GITHUB_API_TOKEN=你的GitHub Token

步骤3:修改前端请求代码

将原来直接请求GitHub API的代码,改为请求自己的API路由:

useEffect(() => {
  const fetchCode = async () => {
    const repoPath = 'Kanav-Arora/DSA-Guide/contents/Binary Search/binary_search.cpp';
    const response = await fetch(`/api/github-proxy?repoPath=${encodeURIComponent(repoPath)}`);
    console.log(response);
    // 获取文件内容
    const content = await response.text();
    console.log(content);
  }
  fetchCode();
}, [cpp])

额外说明

  • 对于公开仓库,其实不需要Token也能请求,但添加Token可以提升API请求速率限制(匿名请求每小时60次,认证后每小时5000次)
  • 你之前在next.config.mjs里的CORS配置可以保留,它仅作用于你的Next.js自身接口,不影响GitHub API的请求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 18:02:43