CSS 不会使用 Node 加载到我的 HTML 代码中.js



我正在尝试使用 Node.js 的 localhost:3000 中的 express() 函数将 CSS 添加到我的 HTML 中。 不幸的是,有些事情很奇怪。我一步一步地按照教程中的步骤进行操作,但我的 css 仍然无法加载。我的样式.csscss文件夹(css/style.css)中。这是我的代码:

app.js(请注意,我使用了app和app1)

var app = require('http').createServer(handler);
var io = require('socket.io').listen(app);
var fs = require('fs');
var express = require('express');
var app1 = express();
var mySocket = 0;
app1.use(express.static('/css'));

app.listen(3000); //Which port are we going to listen to?
function handler (req, res) {
fs.readFile(__dirname + '/index.html', //Load and display outputs to the index.html file
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}

io.sockets.on('connection', function (socket) {
console.log('Webpage connected'); //Confirmation that the socket has connection to the webpage
mySocket = socket;
});
//UDP server on 41181
var dgram = require("dgram");
var server = dgram.createSocket("udp4");
server.on("message", function (msg, rinfo) {
console.log("Broadcasting Message: " + msg); //Display the message coming from the terminal to the command line for debugging
if (mySocket != 0) {
mySocket.emit('field', "" + msg);
mySocket.broadcast.emit('field', "" + msg); //Display the message from the terminal to the webpage
}
});
server.on("listening", function () {
var address = server.address(); //IPAddress of the server
console.log("UDP server listening to " + address.address + ":" + address.port);
});
server.bind(41181);

style.css(css/style.css)

.test
{
color:red;
}

索引.html

<html>
<head>
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<link rel="stylesheet" type="text/css" href="/css/style.css" />
</head>
<body>
<script>
var socket = io.connect('http://localhost:3000');
socket.on('field', function (data) {
console.log(data);
$("#field").html(data);
});
</script>
<div class='test'>Data from C#: </div><div id="field"></div>
</body>
</html>

将静态模块的根目录设置为/css

app1.use(express.static('/css'));

但随后您请求/css/style.css这意味着 Express 在/css/css/style.css中查找文件(请注意,此路径是绝对路径,而不是相对于您的项目)。

将所有内容放在public文件夹中,例如public/css/style.css然后

app1.use(express.static(__dirname + '/public'));

编辑:这是一个最小的工作示例,它服务于索引.html和样式.css(public/css/style.css

)
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.get('/index.html', function(req, res, next) {
res.sendFile(__dirname + '/index.html');
});
app.listen(3000);

最新更新