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

本地应用经ngrok转发后在Google Apps Script中资源路由失败的解决方法

问题描述

我正在开发一款Google Sheet插件,当前应用在localhost:3001环境开发,已经通过ngrok转发该地址。应用能在Google Apps Script中运行,但index.html无法加载assets目录下的资源,求解决办法。

相关代码

Google Apps Script 代码

function getData() {
  const url = "••••••"; 
  const options = {
    method: "get",
    headers: {
      "Content-Type": "application/json",
      "ngrok-skip-browser-warning": "true",

    },

  };

  const response = UrlFetchApp.fetch(url, options);   
  return response.getContentText();
}

function doGet(){
  const html = getData();
  Logger.log(html);
  return HtmlService.createHtmlOutput(html);
}

index.html 代码

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta name="description" content="basic gpx/tcx data analysis app" />
    <title>mycorr</title>
    <script type="module" crossorigin src="/assets/index-CYckigfU.js"></script>
    <link rel="modulepreload" crossorigin href="/assets/react-DNzqxdh-.js">
    <link rel="modulepreload" crossorigin href="/assets/mui-CYjvO3ta.js">
    <link rel="stylesheet" crossorigin href="/assets/react-CM9Skd9z.css">
    <link rel="stylesheet" crossorigin href="/assets/index-CP7RGrzZ.css">
  </head>

  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>

解决办法

问题核心是:你获取的index.html里资源用的是根相对路径(/assets/xxx),当这段HTML在Google Apps Script环境运行时,浏览器会把根路径解析成GAS的域名,而非你的ngrok地址,导致资源请求失败。

方案1:修改前端打包配置生成绝对路径

在你的前端项目(如Vite、Create React App)中,将base配置项设置为你的ngrok完整域名(例如https://abc123.ngrok.io/)。打包后所有assets资源的路径会自动变为绝对路径,浏览器能直接请求到ngrok上的资源。

以Vite项目为例,修改vite.config.js:

export default defineConfig({
  base: 'https://你的ngrok完整域名/',
  // 其他原有配置
})

方案2:在GAS中替换HTML资源路径

如果不想修改前端配置,可以在getData函数获取HTML后,批量替换资源路径:

function getData() {
  const ngrokUrl = "https://你的ngrok完整域名/"; // 替换为实际ngrok地址
  const url = ngrokUrl; 
  const options = {
    method: "get",
    headers: {
      "Content-Type": "application/json",
      "ngrok-skip-browser-warning": "true",
    },
  };

  const response = UrlFetchApp.fetch(url, options);   
  let html = response.getContentText();
  // 全局替换根相对路径为ngrok绝对路径
  html = html.replace(/\/assets\//g, ngrokUrl + "assets/");
  return html;
}

注意:ngrok免费版每次重启会生成新域名,用方案2的话每次都要更新ngrokUrl;如果长期开发,建议用方案1配合ngrok付费版的固定域名,避免频繁修改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 18:15:14