简体   繁体   中英

Express routes work when serving locally but fail once deployed

I am building a blog using Node js and Express and hosting it on firebase. When I serve the website locally everything works just fine and the html is served as expected. But, when I deploy the server the routes no longer work and the html files can't be found. I'm sure it has to do with how firebase deploy hold the html files.

I'm not really sure where to go from here. I can't really find great guidance on how to set up something like this on the firebase docs.

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)

So what is happening is when I deploy the site locally all of the links in my webpage work to other html webpages for my site. When I deploy it on firebase I get 404 errors. I was able to use path.join(__dirname, "../public") and print out all of the files contained there. When i did that these were the files that were there on my local host: [".DS_Store","404.html","about.html","blogs","contact.html","css","five-steps-july-20.html","img","index.html","js","mail","tools.html","vendor"]. After deploying it just returns me a 500 error so I guess that won't help.

Your directories contain absolute paths to your filesystem. Try to use dynamic absolute paths. Change the paths from

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

To

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM