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

授权完成后更新react-apollo中authLink的authorization请求头

解决Github GraphQL API获取token后更新请求头的问题

我懂你的需求——应用初始化完成后,已经成功拿到了access_token,现在要把这个token加到后续所有Github GraphQL API请求的Authorization头里对吧?其实这个问题很好解决,核心就是让请求头的配置能动态读取最新的token,我给你两种实用的方案:

方案一:封装专属请求函数(基于你当前用的request库)

首先,你可以在模块里定义一个变量来存储token,方便后续随时更新:

// 全局/模块级变量,存储最新的access_token
let githubAccessToken = '';

然后在获取token的回调里更新这个变量:

request.post({
  url: 'http://localhost:8080/authorize',
  body: JSON.stringify({ code: '123456789' })
}, function(error, response, body){
  if (!error && response.statusCode === 200) {
    // 解析返回的token数据(根据你后端返回的格式调整)
    const tokenData = JSON.parse(body);
    githubAccessToken = tokenData.access_token;
    console.log('Token已获取,后续请求会自动带上授权头');
  }
});

接下来封装一个专门用于Github GraphQL请求的函数,每次发起请求时自动使用最新的token:

function sendGithubGraphQL(query, variables = {}) {
  return new Promise((resolve, reject) => {
    if (!githubAccessToken) {
      return reject(new Error('请先获取access_token'));
    }
    
    request.post({
      url: 'https://api.github.com/graphql',
      headers: {
        // 动态插入最新的token
        'Authorization': `Bearer ${githubAccessToken}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        query: query,
        variables: variables
      })
    }, function(error, response, body){
      if (error) {
        reject(error);
      } else {
        resolve(JSON.parse(body));
      }
    });
  });
}

之后你发起GraphQL请求就直接用这个函数就行,它会自动处理授权头:

// 示例:查询当前登录用户信息
const userQuery = `
  query {
    viewer {
      login
      name
      avatarUrl
    }
  }
`;

sendGithubGraphQL(userQuery)
  .then(data => console.log('用户信息:', data))
  .catch(err => console.error('请求出错:', err));

方案二:用Axios拦截器(更优雅的现代方案)

如果你愿意换成Axios这类更灵活的HTTP库,可以用请求拦截器来统一处理授权头,不用每次手动设置:

const axios = require('axios');

// 创建Github API的专属实例
const githubApi = axios.create({
  baseURL: 'https://api.github.com/graphql',
  headers: {
    'Content-Type': 'application/json'
  }
});

// 定义存储token的变量
let githubAccessToken = '';

// 添加请求拦截器,自动给所有请求加Authorization头
githubApi.interceptors.request.use(config => {
  if (githubAccessToken) {
    config.headers.Authorization = `Bearer ${githubAccessToken}`;
  }
  return config;
});

// 获取token后更新变量
request.post({
  url: 'http://localhost:8080/authorize',
  body: JSON.stringify({ code: '123456789' })
}, function(error, response, body){
  if (!error && response.statusCode === 200) {
    githubAccessToken = JSON.parse(body).access_token;
  }
});

// 发起GraphQL请求,自动带上授权头
githubApi.post('', {
  query: userQuery
}).then(res => {
  console.log('请求结果:', res.data);
}).catch(err => {
  console.error('请求失败:', err);
});

小提醒

记得要确保在拿到token之后再发起需要授权的请求,不然会返回401未授权错误。如果有需要,可以在请求函数里加个token存在性的判断,提前提示用户完成授权流程。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:05:33