我想通過Node.js使用express()函數在localhost:3000中將CSS添加到我的HTML中。 不幸的是,有些奇怪。我一步一步按照教程中的步驟,但仍然無法加載我的CSS。我的style.css在css文件夾(css/style.css)。這裏是我的代碼:
app.js(請注意,我用的應用程序和應用1)CSS無法使用Node.js加載到我的HTML代碼中
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>
你有沒有在控制檯中的任何錯誤的最小工作的例子嗎?例如,像style.css的404一樣。 – Salketer
'css'文件的URL以'/'開頭。確保'localhost'的根目錄包含'css'文件夾。 –