【问题标题】:No styles are added when rendering the page渲染页面时不添加样式
【发布时间】:2020-01-29 16:35:45
【问题描述】:

我在渲染页面时遇到了样式问题。 在任何其他页面上连接样式都没有问题 这是带有 product.pug 的哈巴狗:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="styles/main.css">
    <title>#{product.product_name}</title>
</head>
<body>
    <header>
        include layout/menu.pug
        include layout/myProfile.pug
    </header>
    <main>
        | there will be data about the product
    </main>
    include layout/footer.pug
</body>
</html>

这是带有 app.js 的代码:

app.get('/product/:productId', (req, res) => {
    if (req.params["productId"] !== undefined &&
        req.params["productId"] > 0) {
        conn.query(`SELECT * 
                    FROM product
                    WHERE product_id = ${req.params["productId"]}`, (err, product) => {
            if(err) {throw err;}
            if(product.length > 0) {
                res.render('product', {
                    userName: req.session.userName,
                    successAuthentication: req.session.successAuthentication,
                    isWorker: req.session.isWorker,
                    product
                })
            } else {
                res.sendStatus(404);
            }
        });
    } else {
        res.sendStatus(404);
    }
});

styles存放在public文件夹中,app用来使用styles

app.use(express.static (path.join(__dirname, 'public')));

任何其他页面的样式都没有问题。 我无法解决这个问题,所以我将不胜感激任何提示

【问题讨论】:

  • 我建议逐位删除部分逻辑/页面,直到找到导致此问题所需的最少代码。那么解决方案可能会更加清晰。

标签: node.js express pug


【解决方案1】:

您可以像下面的代码一样设置您的 express 静态文件夹:

app.use(expresss.static('public'));

现在,您可以尝试在应用根目录中创建 public 文件夹,并将您的 styles 文件夹移动到您的 public 文件夹中,这样就可以正常工作了。

希望对你有帮助。

【讨论】: