You need to enable JavaScript to run this app. 使用Axios调用GitHub GraphQL API返回404 Not Found问题咨询
优惠活动
大模型
产品
解决方案
定价
更多

使用Axios调用GitHub GraphQL API返回404 Not Found问题咨询

问题根因与修正方案

触发404的直接原因

  • 请求URL末尾多余的斜杠:你配置的baseUrl为https://api.github.com/graphql/,GitHub GraphQL API的官方端点为https://api.github.com/graphql,末尾的斜杠会导致路由匹配失败,直接返回404。这也是Postman测试正常、代码跑不通的核心差异点(Postman中你使用的URL未携带末尾斜杠)。

其他会导致请求失败的隐含问题

  • 请求体结构错误:Axios的post方法第二个参数就是原生请求体,会自动完成JSON序列化、匹配Content-Type头。你当前的写法是将已经包含query字段的对象额外序列化后再套入body字段,实际发送的请求体结构为{"body": "{\"query\":\"...\"}"},完全不符合GitHub GraphQL接口要求的{"query": "GraphQL语句"}结构。
  • GraphQL参数格式错误:模板字符串中user(login: ${username})插值后生成的语句未给字符串参数加双引号,解析时会直接报错,正确写法应为user(login: "${username}")。
  • Axios导入方式不适配CommonJS环境:你使用Node.js原生的require语法,却采用了ES模块的解构导入写法const { default: Axios } = require("axios"),部分Axios版本下该写法会拿到undefined,应改为直接导入默认对象const Axios = require("axios")。

修正后的可运行代码

const Axios = require("axios");

const username = "myGithubUsername";
const token = "myGithubPersonalAccessToken";

const requestBody = {
    query: `
    query { 
        user(login: "${username}"){
          name,
          login,
          bioHTML,
          avatarUrl,
          repositories(last: 10){
            nodes{
              name,
              id,
              forkCount
            }
          }
        }
      `
};
// 移除URL末尾多余的斜杠
const baseUrl = "https://api.github.com/graphql";

const headers = {
    "Content-Type": "application/json",
    Authorization: `Bearer ${token}`
};

Axios.post(baseUrl, requestBody, { headers })
    .then((response) => {
        console.log('response', response.data);
    })
    .catch((error) => {
        console.log('error', error.response ? error.response.data : error.message);
    });

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.17 00:24:04