首页 > 解决方案 > 在 res.sendfile express js 上发送 html 和 css 文件

问题描述

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

索引.html

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

索引.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("folderName"));

还有其他可能的选择来解决它吗?

标签: htmlcssnode.jsexpress

解决方案


您可以使用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"

推荐阅读