Node JS配置
我正在尝试配置我的节点js以运行我的html代码。我也在使用bootstrap和Express Js。当我运行节点js时,它没有加载CSS。有人可以帮我这是什么问题。这里是节点js。代码段。
var express = require("express");
var app = express();
var path = require("path");
app.get('/',function(req,res) {
res.sendFile(__dirname + '/home.html')
})
app.use(express.static(__dirname + '/public'))
app.listen(3000);
console.log("Running at Port 3000");
当我直接加载HTML文件时,它正确加载了CSS,但是当我使用节点js加载时,它失败了。这可能是问题的原因吗?
回答如下:检查您的目录结构是否正确,并且已为Node.js授予正确的权限以进入目录并读取文件。
如果您的目录结构如下:
/public
/stylesheets
home.css
home.html
server.js
您的server.js代码如下所示:
var express = require("express");
var app = express();
var path = require("path");
app.get('/',function(req,res) {
res.sendFile(__dirname + '/home.html');
})
app.use(express.static(__dirname + '/public'));
app.listen('3000', function() {
console.log("Listening on port 3000");
});
运行时:
node ./server.js
并在浏览器中访问此URL:
http://localhost:3000/stylesheets/home.css
您将返回home.css文件。