我试图学习node.js并遇到了一些障碍。
我的问题是我似乎无法将外部CSS和JS文件加载到html文件中。
GET http://localhost:8080/css/style.css 404 (Not Found)
GET http://localhost:8080/js/script.css 404 (Not Found)
(这是当所有文件都在应用程序的根目录中时)
有人告诉我要模仿以下应用程序结构,为公共目录添加一条路由,以允许Web服务器为外部文件提供服务。
我的应用程序结构是这样的
domain.com
app/
webserver.js
public/
chatclient.html
js/
script.js
css/
style.css
因此,我的webserver.js脚本位于应用程序的根目录中,而我想访问的所有内容均位于“ public”中。
我还看到了使用path.extname()获取路径中所有文件扩展名的示例。(请参阅最后一个代码块)。
因此,我尝试将新的网站结构与这个path.extname()示例结合在一起,以使网络服务器允许访问我的公共目录中的任何文件,因此我可以呈现引用外部js和css文件的html文件。
。
我的webserver.js看起来像这样。
var http = require('http')
, url = require('url')
, fs = require('fs')
, path = require('path')
, server;
server = http.createServer(function(req,res){
var myPath = url.parse(req.url).pathname;
switch(myPath){
case '/public':
// get the extensions of the files inside this dir (.html, .js, .css)
var extname = mypath.extname(path);
switch (extname) {
// get the html
case '.html':
fs.readFile(__dirname + '/public/chatclient.html', function (err, data) {
if (err) return send404(res);
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data, 'utf8');
res.end();
});
break;
// get the script that /public/chatclient.html references
case '.js':
fs.readFile(__dirname + '/public/js/script.js', function (err, data) {
if (err) return send404(res);
res.writeHead(200, { 'Content-Type': 'text/javascript' });
res.end(content, 'utf-8');
res.end();
});
break;
// get the styles that /public/chatclient.html references
case '.css':
fs.readFile(__dirname + '/public/css/style.css', function (err, data) {
if (err) return send404(res);
res.writeHead(200, { 'Content-Type': 'text/javascript' });
res.end(content, 'utf-8');
res.end();
});
}
break;
default: send404(res);
}
});
在public的情况下,我试图通过var extname =
mypath.extname(path);来获取此目录中的任何文件夹/文件。与我提供的链接类似。
但是目前,当我控制台登录时,“ extname”为空。
有人可以在这里建议我可能需要补充的内容吗?我知道这可以在Express中轻松完成,但是我想知道如何仅依靠Node来实现相同的目标。
我对此表示感谢。
提前致谢。