我正在尝试学习Node.js,但遇到了一些困难。
我的问题是,我似乎无法将外部CSS和JS文件加载到HTML文件中。
(这是当所有文件都在应用程序的根目录中时)。
我被告知要模仿以下应用程序结构,添加一个路由来允许Web服务器为外部文件提供公共目录。
我的应用程序结构如下。
在公共案例中,我正在尝试通过以下方式获取此目录中的任何文件夹/文件: var extname = mypath.extname(path); 类似于我提供的链接。
但是,当我控制台记录它时,'extname'目前为空。
有人可以建议我需要添加或调整什么吗? 我知道在Express中可以轻松完成这个操作,但我想知道如何仅依靠Node来实现相同的事情。
我很感激您的帮助。
提前致谢。
我的问题是,我似乎无法将外部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()示例,使web服务器允许访问公共目录中的任何文件,以便我可以呈现引用外部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);
}
});
在公共案例中,我正在尝试通过以下方式获取此目录中的任何文件夹/文件: var extname = mypath.extname(path); 类似于我提供的链接。
但是,当我控制台记录它时,'extname'目前为空。
有人可以建议我需要添加或调整什么吗? 我知道在Express中可以轻松完成这个操作,但我想知道如何仅依靠Node来实现相同的事情。
我很感激您的帮助。
提前致谢。
send404()
函数之前打印出err
的值,以查看实际错误是什么。 - monsur