html - 在 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");
}
)
我根据一些在线参考尝试了以下选项,但没有任何帮助:
在根目录上传递index.css,因为浏览器应该能够自己加载它。
app.get('/index.css', function(req, res) { res.sendFile(__dirname + "/" + "index.html"); });
创建新文件夹并将我的静态文件(html 和 css)移动到该文件夹下,并将res.sendfile替换为app.use(express.static("folderName"));
还有其他可能的选择来解决它吗?
解决方案
您可以使用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"
推荐阅读
- windows - 如何挂钩 Windows x64、x86 上的任何 API 调用?
- recursion - FP-Growth 算法中的递归
- php - 作曲家没有做出好的动作
- node.js - 尝试将现有的 excel 文件发送到 UI,作为来自节点后端的响应
- javascript - 模态仅在多个按钮上显示最后一个按钮内容
- javascript - 如何使用 Node 和 node-rest-client 发出 Oauth2 REST 请求?
- python - 使用 Selenium 和 Python 在 Chrome 中同时登录多个帐户
- angular - 为什么我的异步函数可以在 Firefox 上运行,但在 Chrome 上却给我一个错误?
- c++ - Xcode 11 头文件问题
- ios - ViewController 交互式过渡平移手势识别器