Express返回public静态文件但根路径/路由未触发问题求助
问题原因
Express 中间件和路由的执行顺序和代码编写顺序完全一致,当前代码存在两个顺序相关问题:
express.static静态资源中间件定义在自定义/路由之前,且express.static默认会将指定目录下的index.html作为根路径/的默认返回资源,收到请求时静态中间件先匹配到对应文件直接返回,请求不会传递到后续路由- 规范上
app.listen应该放在所有路由、中间件配置完成之后再执行,避免服务启动后部分路由还未注册完成
修复方案
调整代码顺序,将自定义路由放在静态资源中间件之前,app.listen放在代码最末尾,修改后参考代码:
// Require packages const express = require("express"); const cookieParser = require("cookie-parser"); const bodyParser = require("body-parser"); const mongoose = require("mongoose"); const ejs = require("ejs"); const path = require("path"); // Create app const app = express(); // Use cookie parser, body parser app.use(cookieParser()); app.use(bodyParser()); // Deal with templating and file serving shenanigans app.engine("ejs", ejs.renderFile); app.set("view engine", "ejs"); app.set("views", path.join(__dirname, "views")); // 自定义路由移到静态资源中间件之前 app.get("/", async (req, res) => { console.log("I am not logged"); res.send("I am not sent"); // Async is needed for a function that occurs here. }) // 静态资源中间件移到路由之后 app.use(express.static(path.join(__dirname, "public"))); // Start server 放到所有配置最后 app.listen(1773, () => { console.log("I hope users aren't using weak passwords!"); });
如果你需要保留原有代码顺序,也可以修改静态资源中间件的配置,禁用根路径默认返回index.html的逻辑:
app.use(express.static(path.join(__dirname, "public"), { index: false }));
内容的提问来源于stack exchange,提问作者willmaybe
相关产品推荐
相关产品推荐

