【问题标题】:Express routes work when serving locally but fail once deployed快速路由在本地服务时有效,但在部署后失败
【发布时间】:2019-11-14 16:03:35
【问题描述】:

我正在使用 Node js 和 Express 构建博客并将其托管在 firebase 上。当我在本地为网站提供服务时,一切正常,并且 html 按预期提供。但是,当我部署服务器时,路由不再起作用,并且找不到 html 文件。我确定这与 firebase deploy 如何保存 html 文件有关。

我不确定从这里去哪里。我真的找不到关于如何在 firebase 文档上设置类似内容的很好的指导。

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

/* Express with CORS */
const app = express()
app.use(cors({ origin: true }))
app.get("/", (request, response) => {
  response.send("Hello from Express on Firebase with CORS!")
})

//File path consts
const publicDir = "/Users/wilson/wildman-talks-fb/public";
const blogDir = "/Users/wilson/wildman-talks-fb/public/blogs";

app.get("/about/", (req, res) =>{
    res.sendFile(path.join(publicDir, "/about.html"));
});

app.get("/contact/", (req, res) =>{
    res.sendFile(path.join(publicDir, "/contact.html"));
});

app.get("/tools/", (req, res) =>{
    res.sendFile(path.join(publicDir, "/tools.html"));
});

app.get("/five-steps-july-20/", (req, res) =>{
    //res.send(path.join(publicDir, "/five-steps-july-20.html"));
    res.sendFile(path.join(publicDir, "/five-steps-july-20.html"));
})

exports.app = functions.https.onRequest(app)

因此,当我在本地部署网站时,我网页中的所有链接都可用于我网站的其他 html 网页。当我在 firebase 上部署它时,出现 404 错误。我能够使用 path.join(__dirname, "../public") 并打印出其中包含的所有文件。当我这样做时,这些是我本地主机上的文件:[".DS_Store","404.html","about.html","blogs","contact.html","css","five -steps-july-20.html","img","index.html","js","mail","tools.html","vendor"]。部署后它只会返回一个 500 错误,所以我想这无济于事。

【问题讨论】:

  • 请编辑问题以提供有关未按您期望的方式工作的更多具体信息。例如,哪些特定 URL 在本地工作但未部署?无效 URL 的响应究竟是什么?
  • 如果您想提供静态内容,您确定不想使用 Firebase 托管吗?它会更便宜、更快。

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


【解决方案1】:

您的目录包含文件系统的绝对路径。尝试使用动态绝对路径。 更改路径

  const publicDir = "/Users/wilson/wildman-talks-fb/public";
  const blogDir = "/Users/wilson/wildman-talks-fb/public/blogs";

  const path = require("path");
  const publicDir = path.join(__dirname, "/public";)
  const blogDir = path.join( __dirname, "/public/blogs");

【讨论】:

  • 我添加了它,但仍然没有。当引用 /about 并且目录名为 /srv 时,我能够打印出 __dirname。如果它复制我的文件夹结构或重新组织它,我不确定它如何存储我发送的文件。
猜你喜欢
  • 1970-01-01
  • 2022-11-03
  • 1970-01-01
  • 2018-11-30
  • 2019-07-12
  • 2022-12-18
  • 2018-12-18
  • 1970-01-01
  • 2021-12-21
相关资源
最近更新 更多