首页 > 解决方案 > 发送公共文件但不调用路由

问题描述

出于某种原因,“/”将 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.
})

没有错误,它只是不起作用。

标签: node.jsexpress

解决方案


您的express.static()线路正在处理请求。如果它看到对 的请求/,那么它会在您express.static()为文件提供的index.html文件夹中查找。如果它找到它,那么它将为该文件提供服务并完成请求 - 不会调用以后的请求处理程序。

如果您希望/路由处理程序被调用,那么您可以:

  1. index.html从公共目录中删除文件
  2. 告诉express.static()index.html匹配app.use(express.static(path.join(__dirname, "public"), {index: false}));
  3. app.get("/", ...)在您的路线之前声明express.static()路线。
  4. 将路由更改为与目录app.get("/", ...)中的内容不匹配的public其他路径,并将您的请求发送到该其他路径。

请记住,Express 按照声明的顺序匹配路由。第一个匹配的获胜。因此,如果express.static()找到匹配项,它会“处理”请求,并且不会在获得机会后声明任何路由。


推荐阅读