【问题标题】:CSS file is not connecting in an express appCSS 文件未在 Express 应用程序中连接
【发布时间】:2023-01-16 23:12:51
【问题描述】:

运行我的 app.js 文件时

const express = require('express');
const path = require('path');
const app = express();

app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'))

app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, '/index.html'));    
});

const port = process.env.PORT || 5000;
app.listen(port, () => {
    console.log(`Serving on port ${port}`)
})

这是我的 index.html 文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet"  href="styles.css" type="text/css" />
</head>
<body>
    <h1> Testing CSS</h1>
</body>
</html>

那么我就无法在页面上观察到CSS文件的变化。但是当我用实时服务器打开 HTML 文件时,我可以看到 CSS 发生了变化,为什么会发生这种情况。

当我运行我的 app.js 文件时,css 没有连接。但是当我打开 HTML 文件时,实时服务器 CSS 文件正在连接。这背后的原因是什么??

【问题讨论】:

    标签: javascript html css node.js express


    【解决方案1】:
    app.use(express.static(path.join(__dirname, 'public')));
    

    将其包含在您的 app.js 中,创建一个名为 public 的文件夹,并将 style.css 放入您的公共目录中。 你的代码将是

        const express = require('express');
        const path = require('path');
        const app = express();
        
        app.set('view engine', 'ejs');
        app.set('views', path.join(__dirname, 'views'))
    
    
        app.use(express.static(path.join(__dirname, 'public'))); //<-here
    
    
    
        app.get('/', (req, res) => {
            res.sendFile(path.join(__dirname, '/index.html'));    
        });
        
        const port = process.env.PORT || 5000;
        app.listen(port, () => {
            console.log(`Serving on port ${port}`)
        })
    

    【讨论】:

      猜你喜欢
      • 2015-05-18
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多