node.js - 发送公共文件但不调用路由
问题描述
出于某种原因,“/”将 public/index.html 发送到浏览器,但 index.js 中的快速路由没有触发。
index.js
// 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.use(express.static(path.join(__dirname, "public")));
// Start server
app.listen(1773, () => {
console.log("I hope users aren't using weak passwords!");
});
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.
})
没有错误,它只是不起作用。
解决方案
您的express.static()
线路正在处理请求。如果它看到对 的请求/
,那么它会在您express.static()
为文件提供的index.html
文件夹中查找。如果它找到它,那么它将为该文件提供服务并完成请求 - 不会调用以后的请求处理程序。
如果您希望/
路由处理程序被调用,那么您可以:
index.html
从公共目录中删除文件- 告诉
express.static()
不index.html
匹配app.use(express.static(path.join(__dirname, "public"), {index: false}));
app.get("/", ...)
在您的路线之前声明express.static()
路线。- 将路由更改为与目录
app.get("/", ...)
中的内容不匹配的public
其他路径,并将您的请求发送到该其他路径。
请记住,Express 按照声明的顺序匹配路由。第一个匹配的获胜。因此,如果express.static()
找到匹配项,它会“处理”请求,并且不会在获得机会后声明任何路由。
推荐阅读
- asp.net - 在aspnet核心中将原始html从文件复制到剃须刀页面?
- sql - Scala如何根据条件将列表拆分为N个列表
- r - 使用列表中的名称作为新创建的数据框的名称(使用分配),但也希望将该名称用于其中的变量
- laravel - laravel 8 的 CKFinder 身份验证问题
- ruby-on-rails - 设计 - 一种用户类型无法登录
- c - 调整结构大小并移动指针后,指针没有显示到他应该指向的地址
- javascript - 如何通过 MongoDB 中包含的单词查找记录
- git - 与自定义合并驱动程序合并时出现 git 缓存错误
- javascript - 焦点功能在控制台中工作,但通过代码
- probability - 如何获得空间和非空间效应的“公平”先验