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

导入googleapis时遇Module not found: Can't resolve 'fs'问题求助

解决方案:将Google Sheets操作移至Next.js API Route

你的问题核心在于:googleapis依赖Node.js核心模块(fs、child_process),这些模块只能在服务器端运行,而你直接在客户端页面组件里导入了包含该库的代码,导致客户端打包时找不到这些模块。下面是具体解决步骤:

1. 将数据提交逻辑改为API Route

Next.js的API Route默认运行在服务器端,天然支持Node.js核心模块,适合处理这类需要调用后端服务的逻辑。

步骤1:创建API Route文件

在pages/api目录下新建submit-data.js(如果没有api目录就先创建),将原来的submitData.js代码修改为以下格式:

import { google } from "googleapis";
import keys from "../../secrets.json";

export default async function handler(req, res) {
  // 只允许POST请求
  if (req.method !== "POST") {
    return res.status(405).json({ message: "仅支持POST请求" });
  }

  const { data } = req.body;

  try {
    // 初始化认证
    const auth = new google.auth.GoogleAuth({
      credentials: {
        client_email: keys.client_email,
        private_key: keys.private_key?.replace(/\\n/g, "\n"),
      },
      scopes: [
        "https://www.googleapis.com/auth/drive",
        "https://www.googleapis.com/auth/drive.file",
        "https://www.googleapis.com/auth/spreadsheets",
      ],
    });

    const sheets = google.sheets({ auth, version: "v4" });
    const sheetName = "DATA";

    // 注意:Google Sheets API要求values是二维数组,这里修正原代码的格式问题
    const response = await sheets.spreadsheets.values.append({
      spreadsheetId: process.env.SHEET_ID,
      range: `${sheetName}!A3:E3`,
      valueInputOption: "USER_ENTERED",
      requestBody: {
        values: [[data.name, data.date]],
      },
    });

    return res.status(200).json({ data: response.data });
  } catch (e) {
    return res.status(500).json({ message: e.message ?? "操作失败" });
  }
}

2. 修改页面组件的调用方式

不再直接导入submitData模块,而是通过fetch调用刚才创建的API Route:

// pages/dashboard/index.js
...
const example = async (e) => {
    e.preventDefault();
    const data = {
      name: nameDisplay,
      date: day,
    };
    try {
      const response = await fetch("/api/submit-data", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ data }),
      });
      const result = await response.json();
      console.log(result);
      alert(result.data.tableRange);
    } catch (e) {
      console.error(e);
    }
...

3. 恢复默认的next.config.js

之前添加的webpack配置不需要保留,因为API Route运行在服务器端,不会涉及客户端打包Node.js核心模块的问题,直接用默认配置即可。

为什么这个方案可行?

  • API Route完全运行在服务器环境,能正常使用googleapis依赖的Node.js核心模块;
  • 页面组件只负责发起HTTP请求,不会接触到任何服务器端专属代码,避免了客户端打包错误;
  • 同时修正了原代码中Google Sheets API参数格式的问题(values需要二维数组),避免后续调用失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 19:33:19