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

在MongoDB Atlas Functions中使用axios报错求助

在MongoDB Atlas Functions中使用Axios出现Z_SYNC_FLUSH未定义错误的解决方法

问题详情

已在MongoDB Atlas Functions中成功添加axios依赖,但运行以下函数时触发报错:

exports = function() {
  const axios = require("axios");
axios.get('https://api.github.com/users/PowellTravis/repos?per_page=100&page=1')
  .then(function (response) {
    onSuccess(response)
  })
  .catch(function (error) {
    console.log(error);
  });
}

报错信息:

failed to execute source for 'node_modules/axios/index.js': FunctionError: failed to execute source for 'node_modules/axios/lib/axios.js': FunctionError: failed to execute source for 'node_modules/axios/lib/core/Axios.js': FunctionError: failed to execute source for 'node_modules/axios/lib/core/dispatchRequest.js': FunctionError: failed to execute source for 'node_modules/axios/lib/adapters/adapters.js': FunctionError: failed to execute source for 'node_modules/axios/lib/adapters/http.js': TypeError: Cannot access member 'Z_SYNC_FLUSH' of undefined
    at node_modules/axios/lib/adapters/http.js:36:10(187)

    at require (native)
    at node_modules/axios/lib/adapters/adapters.js:16:44(41)

    at require (native)
    at node_modules/axios/lib/core/dispatchRequest.js:20:48(77)

    at require (native)
    at node_modules/axios/lib/core/Axios.js:18:55(63)

    at require (native)
    at node_modules/axios/lib/axios.js:17:45(51)

    at require (native)
    at node_modules/axios/index.js:22:45(73)

解决办法

有两种可行方案:

  1. 降级axios版本
    安装axios的0.27.2版本,这是最后一个不依赖Node.js核心zlib模块Z_SYNC_FLUSH属性的稳定版本。MongoDB Atlas Functions的沙箱环境限制了对该属性的访问,高版本axios会因无法调用该属性而加载失败。

  2. 使用内置fetch API替代axios
    MongoDB Atlas Functions原生支持fetch,无需额外依赖,代码示例:

    exports = async function() {
      try {
        const response = await fetch('https://api.github.com/users/PowellTravis/repos?per_page=100&page=1');
        const repoData = await response.json();
        return repoData;
      } catch (err) {
        console.error('请求失败:', err);
        throw err;
      }
    };
    

错误原因

Z_SYNC_FLUSH是Node.js zlib模块的一个常量,高版本axios(如v1.x系列)的HTTP适配器会尝试调用这个常量。但MongoDB Atlas Functions的运行环境是受限的沙箱,并未开放对该核心模块属性的访问权限,导致axios加载时触发类型错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 03:45:42