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

使用Fetch请求调用Github API读取POST返回结果时遇到问题

搞定Github OAuth Token Fetch问题

嘿,我来帮你解决这个困扰!你现在遇到的情况,核心问题有两个——mode: 'no-cors'的浏览器限制,还有一个更关键的安全问题:你把client_secret直接暴露在前端代码里了,这绝对不能这么干!

1. 为什么Fetch读不到响应?

你设置了mode: 'no-cors',这会让浏览器返回一个「不透明响应(opaque response)」。哪怕网络面板能完整看到返回的token,JavaScript也碰不到响应内容、状态码或者headers——这是浏览器的安全机制,防止跨域请求随意获取敏感数据,但你这里完全用错了场景。

2. 正确的做法:用后端代理请求

听我一句劝,绝对不能在前端代码里写client_secret!这就像把你家门钥匙贴在大街上,任何人都能拿着它伪造请求,乱用你的Github应用权限。正确的流程应该是让你的后端服务中转这个请求:

具体步骤:

  • 前端拿到授权码code后,把它发给你自己的后端接口(比如/api/github/get-token)
  • 后端收到code后,再偷偷向Github的token接口发送POST请求,带上client_id、client_secret这些敏感信息
  • 后端拿到Github返回的token后,再把它传给前端

后端示例(Node.js/Express):

const express = require('express');
const fetch = require('node-fetch');
const app = express();
app.use(express.json());

// 后端接口,专门用来拿Github token
app.post('/api/github/get-token', async (req, res) => {
  const { code } = req.body;
  // 这里的密钥只存在后端,绝对不能泄露给前端
  const clientId = '你的Github Client ID';
  const clientSecret = '你的Github Client Secret';
  const redirectUri = 'http://localhost:3000/';

  try {
    const githubRes = await fetch('https://github.com/login/oauth/access_token', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      body: JSON.stringify({
        client_id: clientId,
        client_secret: clientSecret,
        code: code,
        redirect_uri: redirectUri,
        state: 'react'
      })
    });
    const tokenData = await githubRes.json();
    res.json(tokenData);
  } catch (err) {
    res.status(500).json({ error: '获取Token失败,请重试' });
  }
});

app.listen(4000, () => console.log('后端服务跑在http://localhost:4000啦'));

前端修改后的请求代码:

// 把code发给自己的后端,而不是直接请求Github
fetch('http://localhost:4000/api/github/get-token', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ code: code }) // 这里只传code,敏感信息全在后端
})
.then(res => res.json())
.then(data => {
  console.log('终于拿到Token啦:', data.access_token);
  // 接下来就可以用这个Token调用Github API啦
})
.catch(err => console.error('请求出错:', err));

3. 如果你非要前端直接请求(极度不推荐!)

要是你因为特殊情况必须前端直接请求,那首先得删掉mode: 'no-cors',然后设置Accept: 'application/json'让Github返回JSON格式的响应。但再次强调:这样会把client_secret彻底暴露给所有人,你的Github账号风险会非常大!

修改后的前端代码(仅作参考,别真的在生产环境用):

fetch('https://github.com/login/oauth/access_token', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  body: JSON.stringify({
    client_id: '你的Client ID',
    client_secret: '你的Client Secret', // 这里会泄露!!!
    code: code,
    redirect_uri: 'http://localhost:3000/',
    state: 'react'
  })
})
.then(res => res.json())
.then(data => {
  console.log('Token:', data.access_token);
})
.catch(err => console.error(err));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 04:11:04