通过mongoose从mongoDB请求单个文档后,图像和CSS链接断开



大家好,找到我的问题了。我正在联系这个社区,希望你能帮助我解决Mongoose/EJS遇到的问题。

只是想在我解释这个问题之前说。我是一个新手,所以这个问题对大多数人来说可能很简单,解释得很糟糕,所以很抱歉。所以问题是,我试图通过mongose使用mongoDB:id来显示产品详细信息页面。

因此,数据返回到浏览器正常,但CSS和IMAGE链接已断开。更令人沮丧的是,这些链接在所有其他页面上都能很好地工作!

在使用Morgan时,我可以看出问题出在他们的Paths上。

用于从DB检索产品的/products/:id路径也被预先设置为CSS和图像文件的路径,这不是我们的意图,因此错误地呈现了路径,从而断开了链接。

我想我希望我已经包含了我认为完全理解问题所需的所有文件,但如果需要,我很乐意提供进一步的代码。

谢谢你花时间阅读这篇文章,我期待着一个更大的大脑来拯救我。

干杯!

const express = require("express");
const app = express();
const Morgan = require("Morgan");
const mongoose = require("mongoose");
const Product = require("./models/product");
const dbURI =
"mongodb+srv://xxxxxx@xxxxx/test-db/retryWrites=true&w=majority";
mongoose
.connect(dbURI)
.then((result) => app.listen(3000),
console.log("connected to mongodb (products) & listening for requests on port: 3000"))
.catch((err) => console.log(err));
// templating engine
app.set("view engine", "ejs");
// middleware and static files
app.use(express.static(__dirname + "/public"));
app.use(Morgan("dev"));
app.use(express.urlencoded({ extended: true })); 

=======================================================================
**// details.ejs**
<%- include('./partials/head.ejs') %> 
<body>
<main class="body-main">
<!-- ==========   Header =============->
<!-- <%- include('./partials/navbar.ejs') %> →
<div class="promotion-panel-lower">
<h1><%=product.title %></h1>
<div class="promo-grid-item">
<div class="product-name">
<%=product.title %>
</div>
<img src=./images/<%=product.img %>  alt=<%=product.title %> class="photo" />
<h4 class="prices-from">prices from:<%=product.price %></h4>
</div>
</div>
<!-- =========== footer ============ -->
<%- include('./partials/footer.ejs') %>
=======================================================================
// DOC DETAIL REQUEST
app.get("/products/:id", (req, res) => {
const id = req.params.id;
Product.findById(id)
.then((result) => {
res.render("details", { title: "Details", product: result });
})
.catch((err) => {
throw err;
}); });
=======================================================================
// Terminal
// it should look like this 
GET /products/62004ee85f4bcd160b832540 304 282.060 ms - -
GET /css/css-reset.css 404 7.488 ms - 17548
GET /css/style.css 404 6.081 ms - 17548
GET /images/backpack2.jpg 404 7.840 ms - 17548
// BUT here’s the result. i.e. /products/ included to my PUBLIC path CSS and images > 
rendering those links obsolete
GET /products/62004ee85f4bcd160b832540 304 282.060 ms - -
GET /products/css/css-reset.css 404 7.488 ms - 17548
GET /products/css/style.css 404 6.081 ms - 17548
GET /products/images/backpack2.jpg 404 7.840 ms - 17548
=======================================================================

我还没有详细查看您的所有代码。

首先,您是否尝试过删除<img src=./images/<%=product.img %>中斜线前面的点?试试这个:<img src=/images/<%=product.img %>

在我看来,你的images文件夹似乎在你的公用文件夹的根目录中,写/而不是./是有意义的。

最新更新