如何将 css 应用到 node.js?

How to apply css to to node.js?

在此代码中,我将 html 文件调用到 app.js,css 样式未应用于 html,但当我打开 html 没有应用 app.js 样式的单独路径,代码如下:

const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require('mongoose');

const app = express();

app.set('view engine', 'ejs');

app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(express.static("public"));

mongoose.connect("mongodb://localhost:27017/aqeldb1", {useNewUrlParser: true});

app.route("/order")

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

});

app.listen(3000, function() {
  console.log("Server started on port 3000");
});

您需要将 .css 文件所在的目录设置为 static 否则 /index.html 在通过 /index.html 加载时将无法访问它们快递服务器。

app.use(express.static("directory/that/you/want/to/be/publicly/accessible"));  <-- here you keep .css, and clientside .js files.

如果您不想添加另一个静态目录,也可以将 .css 文件放在 public 文件夹中。一个好的方法是将所有包含 view 文件(.html、.css、.js)的目录设为静态。

在您的主 .js 文件中使用:

app.use('/css',express.static(__dirname +'/css'));

在您的主 .html 文件中使用:

<link rel="stylesheet" type="text/css" href="css/style.css" />   

请将 .css 文件保存在 public 文件夹中

尝试申请app.use(express.static('public'));