我最近开始通过创建一个简单的待办事项列表来学习 Express.js 和 mongoose,现在我被一个基本的东西困住了。
当我尝试根据 URL 参数在动态路由中呈现 EJS 文件时,我无法应用stylesheet.css
存储在public
EJS 文件夹中的文件,并且浏览器控制台中显示了以下错误消息。错误信息:
Refused to apply style from 'http://localhost:3000/mylist/css/styles.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
当然,URL 请求是http://localhost:3000/mylist/css/styles.css
.
另一方面,在主路由中渲染的同一个 EJS 文件能够访问stylesheet.css
. 请求 URL 是http://localhost:3000/css/styles.css
.
所以我想无论我尝试呈现什么,请求 URL 都必须http://localhost:3000/css/styles.css
在我的文件结构中。但是,当我在基于 URL 参数的动态路由中呈现为 EJS 时,我不知道如何摆脱mylist
from 。http://localhost:3000/mylist/css/styles.css
我的代码有什么问题?你如何解决它?
文件结构:
应用程序.js
const express = require("express");
const mongoose = require("mongoose");
const app = express();
app.set('view engine', 'ejs');
app.use(express.static("/public"));
mongoose.connect("mongodb://localhost:27017/todolistDB", {useNewUrlParser: true, useUnifiedTopology: true});
const itemsSchema = mongoose.Schema({ name: String });
const customListsSchema = mongoose.Schema({ name: String, items: [itemsSchema] });
const Item = mongoose.model("Item", itemsSchema);
const CustomList = mongoose.model("CustomList", customListsSchema);
app.get("/", (req, res) => {
Item.find((err, foundItems) => {
if (!err) {
res.render("list", { listTitle: "Today", newListItems: foundItems });
}
});
});
app.get("/mylist/:customListName", (req, res) => {
const customListName = req.params.customListName;
CustomList.findOne({ name: customListName }, (err, foundCustomList) => {
if (!err) {
if (foundCustomList) {
res.render("list", {
listTitle: foundCustomList.name,
newListItems: foundCustomList.items
});
} else {
const customList = new CustomList({ name: customListNamem });
customList.save((err) => {
if (!err) {
res.redirect("/mylist/" + customListName);
}
});
}
}
});
});
列表.ejs:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>To-Do List</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<div class="box" id="heading">
<h1> <%= listTitle %> </h1>
</div>
<div class="box">
<form action="/delete" method="post">
<% newListItems.forEach((newListItem) => { %>
<div class="item">
<input type="checkbox" name="checkbox" value="<%= newListItem._id %>" onchange="this.form.submit()">
<p><%= newListItem.name %></p>
</div>
<% }); %>
</form>
<form class="item" action="/" method="post">
<input type="text" name="newItem" placeholder="New Item" autocomplete="off">
<button type="submit" name="listName" value="<%= listTitle %>">+</button>
</form>
</div>
</body>
</html>
我也尝试并替换app.use(express.static("/public"));
为app.use(express.static(__dirname + "/public"));
,但它也不起作用。