【问题标题】:JS not found - express app - cloud functions找不到JS - 快递应用 - 云功能
【发布时间】:2021-11-06 16:29:58
【问题描述】:

我正在使用带有 express js 的 Google 云功能来提供一些 HTML 文件。我的 js 文件没有显示在浏览器中。它说 404 未找到。

我的文件夹结构

我的 HTML 文件:

    <html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script type="module" src="/public/js/auth.js"></script>
  </head>
  <body>
    <div class="content__container">
      <h1>Hello world</h1>
    </div>
    <script src="/public/js/main.js"></script>
  </body>
</html>

我的 app.js

const functions = require("firebase-functions");
const express = require("express");
const path = require("path");


const app = express();

app.use("/js", express.static(path.join(__dirname, "public/js")));

exports.admin = functions.https.onRequest((req, res) => {
  res.sendFile(path.join(__dirname, "public", "admin.html"));
});

调用云函数admin时浏览器报错

函数目录

【问题讨论】:

  • 你试过用`src="main.js"`代替`src="/public/js/main.js"`吗?
  • 是的,它不起作用

标签: javascript node.js firebase express google-cloud-functions


【解决方案1】:

您从哪里暴露了 Express 应用程序?必须有一个如下所示的 HTTP 函数:

const app = express()
app.use("/js", express.static(path.join(__dirname, "public/js")));

exports.api = functions.https.onRequest(app);
// This is missing? or you are not requesting at this URL

添加上述功能后,您的 JS 文件应该可以在以下 URL 获得:

'http://localhost:5001/photography-5b191/us-central-1/api/js/main.js'
// notice the function name ('api' in this case) ---->^^^

您共享的网络日志中的 URL 中缺少暴露 Express 应用的函数名称。

【讨论】:

  • 我不知道它为什么不见了。因为那个 url 正在渲染 html 但不显示 js 文件。
  • @ShahirRiaz 该 URL 将呈现,因为您有一个 API 端点。您没有通过任何功能公开公共目录吗?你能用你拥有的所有云功能更新你的问题吗?
  • 我正在使用exports.api = functions.https.onRequest(app);,但我创建了另一个函数adminadmin.html 发送到浏览器。
  • 有什么更好的解决方案?
  • @ShahirRiaz 尝试添加 api 函数并将脚本 URL 更改为:&lt;script src="'http://localhost:5001/photography-5b191/us-central-1/api/js/main.js'"&gt;&lt;/script&gt;
【解决方案2】:

我想你忘了在你的 js 文件中声明 app

const app = express();

在您的 HTML 文件中:

<script src="./js/main.js">

如果js 是您的静态/公共目录:

<script src="./main.js">

另外,在你的 js 文件中:

res.sendFile(path.join(__dirname, "admin.html"));

【讨论】:

  • 我更正了这个问题,在我声明的代码中
  • 先试试这些。
猜你喜欢
  • 2018-01-03
  • 2019-08-04
  • 1970-01-01
  • 2019-08-05
  • 1970-01-01
  • 1970-01-01
  • 2019-08-15
  • 2020-06-27
  • 2020-10-20
相关资源
最近更新 更多