【问题标题】:Sending both html and css file on the res.sendfile express js在 res.sendfile express js 上发送 html 和 css 文件
【发布时间】:2019-09-03 20:34:17
【问题描述】:

我无法在 express.js 中的 res.sendfile 上同时发送 css 和 html 文件。

index.html

    <div class="hdngTab">
    <h1 style="align-content: center">Automation Utility</h1>
    </div>

index.css

    .hdngTab{
    background-color: rgb(60, 120, 120);
    box-sizing: border-box;
    border:  solid rgb(60, 120, 120);
    text-align: center
    }

index.js

    const express = require("express");
    const app = express();
    const http = require("http").Server(app).listen(3000);

    console.log("Server Started");

    app.get("/", function (req, res) {
    res.sendFile(__dirname + "/index.html");
    }
    )

我根据一些在线参考尝试了以下选项,但没有任何帮助:

  1. 在根目录传递 index.css,因为浏览器应该能够自己加载它。

    app.get('/index.css', function(req, res) {
    res.sendFile(__dirname + "/" + "index.html");
    });
    
  2. 创建新文件夹并将我的静态文件(html 和 css) 移动到该文件夹​​下,并将 res.sendfile 替换为 app.use(express .static("文件夹名"));

还有其他可能的解决方法吗?

【问题讨论】:

    标签: html css node.js express


    【解决方案1】:

    您可以使用express.static 来处理静态文件,例如:

    假设你的文件夹结构:

    app.js
    |    +-- public
    |    |   +-- css
    |    |   |   +-- mystyle.css
    
    const express = require("express");
    const app = express();
    
    // using express you don't need this
    // const http = require("http").Server(app).listen(3000);
    
    // server your css as static
    app.use(express.static(__dirname + 'public'))
    
    console.log("Server Started");
    
    app.get("/", function (req, res) {
      res.sendFile(__dirname + "/index.html");
    })
    
    // start your server
    app.listen(3000, () => console.log('Server started at port 3000'))
    

    在你的 html 中

    <link href="css/mystyle.css"
    

    【讨论】:

      【解决方案2】:

      除了这一行之外,其他一切都保持不变-

      //将你的css作为静态服务器 app.use(express.static(path.join(__dirname, "public")));

      【讨论】:

        猜你喜欢
        • 2015-06-20
        • 2021-11-09
        • 1970-01-01
        • 2020-12-09
        • 1970-01-01
        • 2016-05-26
        • 1970-01-01
        • 1970-01-01
        • 2014-11-08
        相关资源
        最近更新 更多