node.js渲染html无css,Node.js-外部JS和CSS文件(仅使用node.js不表达)

我试图学习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来实现相同的目标。

我对此表示感谢。

提前致谢。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值