您的代码有几个问题。
- 您的服务器没有指定要监听的端口,将无法运行。
- 正如Eric指出的那样,您的案例条件将失败,因为URL中未显示“ public”。
- 您在js和CSS响应中引用的变量“ content”不存在,应该是“ data”。
- 您的CSS内容类型标头应为text / css而不是text / javascript
- 无需在主体中指定“ utf8”。
我已经重新编写了您的代码。注意我不使用大小写/开关。如果不是这样,我宁愿简单得多,如果您愿意,可以将它们放回去。url和path模块在我的重写中不是必需的,因此已将其删除。
var http = require('http'), fs = require('fs');http.createServer(function (req, res) { if(req.url.indexOf('.html') != -1){ //req.url has the pathname, check if it conatins '.html' fs.readFile(__dirname + '/public/chatclient.html', function (err, data) { if (err) console.log(err); res.writeHead(200, {'Content-Type': 'text/html'}); res.write(data); res.end(); }); } if(req.url.indexOf('.js') != -1){ //req.url has the pathname, check if it conatins '.js' fs.readFile(__dirname + '/public/js/script.js', function (err, data) { if (err) console.log(err); res.writeHead(200, {'Content-Type': 'text/javascript'}); res.write(data); res.end(); }); } if(req.url.indexOf('.css') != -1){ //req.url has the pathname, check if it conatins '.css' fs.readFile(__dirname + '/public/css/style.css', function (err, data) { if (err) console.log(err); res.writeHead(200, {'Content-Type': 'text/css'}); res.write(data); res.end(); }); }}).listen(1337, '127.0.0.1');console.log('Server running at http://127.0.0.1:1337/');


