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

使用Axios调用GraphQL时出现Network Error与AxiosError问题

问题分析与解决方案

1. 核心错误原因:CORS 策略限制

Access to XMLHttpRequest at 'https://test.com' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

这个错误是浏览器同源策略导致的:你的前端页面运行在http://localhost:3000,请求的目标服务器是https://test.com,属于跨域请求。浏览器会先发送OPTIONS预请求,若服务器没有返回正确的CORS响应头,就会拦截请求。

2. 前端代码的两处错误

你的Axios请求配置存在格式问题,会导致请求无法被服务器正确解析:

  • headers不应该放在data对象里,需作为Axios配置的顶级属性
  • GraphQL规范中,变量参数的键名是variables,不是vars

同时还要修正HTML的脚本引入顺序,避免axios is not defined报错。

修正后的前端JS代码

const headers = {
  "content-type": "application/json",
  Authorization: "myToken",
};

const query = `
query($id: ID!) {
  workspace(id: $id) {
    name
    company {
      name
    } 
  }
}`;
let variables = { id: "123456" };

// 绑定点击事件,实现点击触发请求
document.getElementById('myID').addEventListener('click', () => {
  axios({
    url: "https://test.com/graphql",
    method: 'POST', // 显式指定POST方法(Axios默认是GET)
    headers: headers, // 移到配置顶级
    data: {
      query,
      variables, // 修正变量键名
    },
  })
  .then((res) => console.log(res))
  .catch((err) => console.log(err));
});

修正后的HTML代码

<!DOCTYPE html>
<html lang="en"> 
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="index.css">
  <title>My Class</title>
</head>
<body>
     <p class="myClass" id="myID">Click Here</p>

<!-- 先引入Axios,再引入业务脚本 -->
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="index.js"></script>
</body>
</html>

3. 服务端(Node-Express)CORS配置

跨域问题必须在服务端解决,通过配置CORS中间件实现:

步骤1:安装cors包

npm install cors

步骤2:在Express应用中启用CORS

const express = require('express');
const cors = require('cors');
const app = express();

// 开发环境配置:允许指定前端域名访问(推荐)
app.use(cors({
  origin: 'http://localhost:3000', // 你的前端运行地址
  credentials: true, // 若请求携带Authorization或Cookie,必须开启
  allowedHeaders: ['Content-Type', 'Authorization'] // 允许的请求头
}));

// 生产环境建议:仅允许指定的正式域名,例如
// app.use(cors({ origin: 'https://your-official-domain.com' }))

// 解析GraphQL的JSON请求体
app.use(express.json());

// 你的GraphQL路由处理逻辑
app.post('/graphql', (req, res) => {
  // 处理GraphQL查询并返回结果
});

app.listen(3001, () => {
  console.log('Server running on port 3001');
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 22:37:41