为什么无法识别外部样式表/脚本? 内联css / js可以正常工作。
文件
server.js
var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
fs = require('fs')
app.listen(8888);
function handler(req, res) {
// console.log(__dirname + 'index.html');
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
var lastPosition = {
x: 0,
y: 0
}; // whatever default data
io.sockets.on('connection', function (socket) {
socket.emit('update_position', lastPosition);
socket.on('receive_position', function (data) {
lastPosition = data;
socket.broadcast.emit('update_position', data); // send `data` to all other clients
});
});
答案 0 :(得分:0)
我强烈建议您将Express用于http服务器实现。但是,如果您真的想使用内置库,则应该执行以下操作,以便同时提供外部文件:
const fs = require('fs');
const http = require('http');
const path = require('path');
const app = http.createServer(handler);
app.listen(8888, function () {
console.log('Server started listening.');
});
function handler(req, res) {
const requestPath = req.url.substring(1) || 'index.html';
const filePath = path.join(__dirname, requestPath);
fs.readFile(filePath, 'utf8', function (err, contents) {
if (err) {
res.writeHead(404);
res.end('<h1>Not Found</h1>');
} else {
res.writeHead(200);
res.end(contents);
}
});
}