在res.sendfile express js上发送html和css文件

Sending both html and css file on the res.sendfile express js

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

index.html

1
    <h1 style="align-content: center">Automation Utility

index.css

1
2
3
4
5
6
    .hdngTab{
    background-color: rgb(60, 120, 120);
    box-sizing: border-box;
    border:  solid rgb(60, 120, 120);
    text-align: center
    }

index.js

1
2
3
4
5
6
7
8
9
10
    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");
    }
    )

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

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

    1
    2
    3
    app.get('/index.css', function(req, res) {
    res.sendFile(__dirname +"/" +"index.html");
    });

  • 创建新文件夹并将我的静态文件(html和css)移动到该文件夹??下,并将res.sendfile替换为app.use(express.static(" folderName"));

  • 还有其他解决方案吗?


    除此行以外,其他所有内容均保持不变-

    //将您的CSS设置为静态
    app.use(express.static(path.join(__dirname,"public")));


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

    假设您的文件夹结构:

    1
    2
    3
    4
    app.js
    |    +-- public
    |    |   +-- css
    |    |   |   +-- mystyle.css
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    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

    1
    <link href="css/mystyle.css"